You may have to refresh the page after editing. Also see Style Guide and Notes.

Task English Python Chicken Javascript C

Numerical Tower? Does the language support the full numerical tower? ± I'm taking the liberty of describing the English language entry in the PLR here. You can find more information on the Numeric Tower by clicking the link in the task heading.



The first line of a comment should be a short general description of the task. A detailed description should follow after a blank line.



Comments are used to give a general description of the task or solution. If you were to view this document as the code extracts from a book, the English language comments would be the text between. They should be as descriptive as possible while remaining general enough to encompass all the languages featured. Where this is not possible a note should be added.



Code is used for describing a specific algorithm in English. This has multiple benefits, mainly it will help beginners learn algorithms.





± Yes (with module: numbers?)



The Python Standard Library - numbers

PEP: 3141

± Yes (with egg: numbers) Chicken FAQ

R5RS

± Not available with standard Javascript. github

± hello world



±

Integer A whole number ± A data type representing a subset of the mathematical integers. The number 42 is an integer.











± a = 42

type(a)

>>> <type 'int'>

± (define a 42)

(integer? a)

>>> #t

± a = 42

typeof a

>>> "number"

± int a = 42;



C Data Types

± Convert to integer.

#include <stdio.h>



int main() {

int a;

float b = 3.14;

a = (int) b;

printf("%d

", a);

}

±

Numeral Systems Numeral systems describe ways to express numbers in writing. ±

Decimal Decimal is a base 10 number system. ± Decimal is a base 10 numbering system. It is the most widely used numbering system. It is usually assumed that numbers are presented in decimal form. 101 in decimal is equal to 101 in decimal.















± Decimal is default and doesn't have to be specified. 101

>>> 101

± Decimal is default and doesn't have to be specified. #d101

>>> 101

101

>>> 101

Chicken Wiki

± Decimal is default and doesn't have to be specified. 101

>>> 101

± Decimal is default and doesn't have to be specified. #include <stdio.h>



int main() {

int a = 101;

printf("%d

", a);

}

>>> 101

±

Task English Python Chicken Javascript C

Division

± Division is the inverse of multiplication. Eight divided by five equals 1.6.

Eight divided by five, divided by three gives us .533.



± Currently in the process of changing the division operators. Best to use the new ones to avoid maintaining backward compatibility, do that by importing division from the __future__ module (2 underscores before and after future) from __future__ import division

8 / 5

>>> 1.6000000000000001

8 / 5 / 3

>>> 0.53333333333333333

Python Gotchas

± (/ 8 5)

>>> 1.6

(/ 8 5 3)

>>> 0.533333333333333

± 8 / 5

>>> 1.6

8 / 5 / 3

>>> 0.5333333333333333

± #include <stdio.h>



int main() {

float a = 8.0/5;

printf("%f

", a);

}

>>> 1.600000

±

Max

± The highest number in a sequence. The maximum value for the numbers 3, 7 and 42 is 42.







± max(3, 7, 42)

>>> 42

± (max 3 7 42)

>>> 42

± Array.prototype.max = function(){

return Math.max.apply({},this)

}

[3, 7, 42].max()

>>> 42

DZone Snippets

± #include <stdio.h>



int max(int *array_ptr) {

int ii;

int arrayLength = sizeof(array_ptr) / sizeof(int);

int maximum_value = array_ptr[0];

for (ii=0; ii <= arrayLength; ii++)

if (array_ptr[ii] > maximum_value) {

maximum_value = array_ptr[ii];}

return maximum_value;

}



int main() {

int a[] = {3, 5, 1};

int biggest = max(a);

printf("%d

", biggest);

}

>>> 5

±

Min

± The lowest number in a sequence. The minimum value for the numbers 3, 7 and 42 is 3.



± min(3, 7, 42)

>>> 3

± (min 3 7 42)

>>> 3

± Array.prototype.min = function(){

return Math.min.apply({},this)

}

[3, 7, 42].min()

>>> 3

DZone Snippets

± #include <stdio.h>



int min(int *array_ptr) {

int ii;

int arrayLength = sizeof(array_ptr) / sizeof(int);

int minimum_value = array_ptr[0];

for (ii=0; ii <= arrayLength; ii++)

if (array_ptr[ii] < minimum_value) {

minimum_value = array_ptr[ii];}

return minimum_value;

}



int main() {

int a[] = {3, 1, 5};

int smallest = min(a);

printf("%d

", smallest);

}

>>> 1

±

Comparison Operators

±

Is Not Compare identity ± Are two objects not the same object? It is false that 2 is not 2.



± 2 is not 2

False



Python Library Reference - Comparisons

± (not (eqv? 2 2))

>>> #f



± 2 !== 2

>>> false

± #include <stdio.h>



int main ( ) {

int a[3] = {1, 2, 3};

int b[3] = {1, 2, 3};

int c = 42;

int d = 42;

printf("%i %i

", a != b, c != d);

}

>>> 1 0

±

Advanced Math More advanced mathematical functions. ±

Variables, Symbols and Names

±

Task English Python Chicken Javascript C

Case Sensitive? Are names/symbols in the language case sensitive? ± Only by convention. The first letter of each sentence is capitalized as well as proper names and places. There are many other rules for capitalization as well.



However these rules can be broken most notably by ALL CAPITAL LETTERS indicating importance or failure to observe the caps lock key, or in CaMel CaSE indicating immaturity or epilepsy. Either deviation could cause seizure or spontaneous outburst of rage by readers, best to avoid. This segment was brought to you by Jack Trades.



± Yes ± Yes ± Yes ± Yes #include <stdio.h>



int main() {

int a = 101;

int A = 100;

printf("%d, %d

", a, A);

}

>>> 101, 100

±

Names must start with a letter?

± Virtually all words start with a letter. Notable exceptions to this are text message shorthand like 2nite, 4ever and the cryptic nonsense of 1337 speak.



Once again using words that do not start with a letter is frowned upon and could lead to internet grammar Nazi's hunting you down.

± Yes (or _) ± No

Names must not start with a '#' ± Yes (or _) ± Yes (or _ or $) ±

Assigning Variables

± How to assign a value to a symbol. Let the letter a represent the number 42.







± a = 42

a

>>> 42

± (define a 42)

a

>>> 42

± var a = 42

a

>>> 42

± #include <stdio.h>



int main() {

int a = 42;

printf("%d

", a);

}

>>> 42

±

Local Variables (Lexical Scoping)

± Are variables defined within the body of a function available outside that function? test is a function which has an internal variable a that equals

7 and returns a plus 35 when called. The variable a does not

exist outside the scope of the test function.







± def test():

a = 7

return a + 35

test()

>>> 42

a

>>> NameError: name 'a' is not defined

± (define (test)

(define a 7)

(+ a 35))

(test)

>>> 42

a

>>> Error: unbound variable: a



±

(define (test3)

(let ((a 7))

(+ a 35)))

(test3)

>>> 42

a

>>> Error: unbound variable: a



± function test() {

var a = 7

return a + 35

}

test()

>>> 42

a

>>> ReferenceError: a is not defined

± #include <stdio.h>



int aFunc() {

int a = 42;

}



int main() {

printf("%d

", a);

}

>>> error: ‘a’ undeclared (first use in this function)

±

Global Variables

± Defining a variable that is accessible throughout the program. Let a equal 5. a shall be accessible everywhere.







± Variables defined at the top-level are global.

Set a global variable, this is usually considered bad form: a = 5

def printGlobalVar():

print a

printGlobalVar()

>>> 5

def setGlobalVar():

global b

b = 5

setGlobalVar()

b

>>> 5





± Variables defined at the top-level are global

Set a global variable, this is usually considered bad style: (define a 5)

(define (printGlobalVar)

(print a))

(printGlobalVar)

>>> 5

(define (setGlobalVar)

(set! b 5))

(setGlobalVar)

b

>>> 5



± Variables defined at the top-level are global. a = 5

function printGlobalVar() {

return a

}

printGlobalVar();

>>> 5



function setGlobalVar() {

b = 5

}

setGlobalVar()

b

>>> 5

± Variables defined at top-level are global #include <stdio.h>



int a = 42;



int main() {

printf("%d

", a);

}

>>> 42

±

Named Lets Named lets are a powerful feature, useful for emulating a number of constructs. ± Named lets are a powerful feature, useful for emulating a number of constructs.

± Python does not support named lets. ± This form is syntactic sugar for a letrc (let countdown ((n 3))

(if (= n 0) (print "Liftoff")

(begin

(print n)

(countdown (- n 1)))))

>>> 3

>>> 2

>>> 1

>>> Liftoff

Teach Yourself Scheme in Fixnum Days

± Javascript does not support named lets. ± C does not support named lets. ±

Modifying Variables

±

Setting Variables

± Setting the value of a variable. Let a equal 1.

The value of a is 1.

Let a equal 'hello'.

The value of a is the string 'hello'.







± a = 1

a

>>> 1

a = "hello"

a

>>> "hello"

± Unlike most Schemes set! is allowed to set an undefined variable. However it is usually good practice to define your variables with define and change them with set! as set! is more explicit. (define a 1)

a

>>> 1

(set! a "hello")

a

>>> "hello"



Chicken Wiki - Extensions to the Standard

± a = 1

a

>>> 1

a = "hello"

a

>>> "hello"

± #include <stdio.h>



int main() {

int a = 7;

a = 42;

printf("%d

", a);

}

>>> 42

±

Setting Multiple Variables

± Setting multiple variables to multiple values. Let a, b and c equal the numbers 1, 2 and 3 respectively.

A list of a, b and c equals (1, 2, 3).

If a, b and c equal 5, 10 and 15 respectively.

Then a list of a, b and c equals (5, 10, 15).







± a, b, c = 1, 2, 3

[a, b, c]

>>> [1, 2, 3]

a, b, c = 5, 10, 15

[a, b, c]

>>> [5, 10, 15]

± (define-values (a b c) (values 1 2 3))

(list a b c)

>>> (1 2 3)

(set!-values (a b c) (values 5 10 15))

(list a b c)

>>> (5 10 15)



Chicken Wiki - set!-values

± a = 1, b = 2, c = 3;

[a, b, c]

>>> [1, 2, 3]

a = 5, b = 10, c = 15;

[a, b, c]

>>> [5, 10, 15]

± Multiple variables can only be set to one value. #include <stdio.h>



int main() {

int a, b, c;

a = b = c = 42;

printf("%d, %d, %d

", a, b, c);

}

>>> 42, 42, 42

±

Incrementing

± Increment the value of a variable. Let a equal 1.

Add 1 to a.

The value of a is now 2.

Add 2 to a.

The value of a is now 4.







± a = 1

a += 1

a

>>> 2

a += 2

a

>>> 4

± (define a 1)

(set! a (add1 a))

a

===> 2

(set! a (+ a 2))

a

===> 4



Chicken Wiki - Unit Library

± a = 1;

a

>>> 1

a += 1;

a

>>> 2

a++;

a

>>> 3

± #include <stdio.h>



int main() {

int a = 6;

a += 1;

printf("%d

", a);

}

>>> 7

±

Decrementing

± Decrement the value of a variable. Let a equal 4.

Subtract 1 from a.

The value of a is now 3.

Subtract 2 from a.

The value of a is now 1.







± a = 4

a -= 1

a

>>> 3

a -= 2

a

>>> 1

± (define a 4)

(set! a (sub1 a))

a

>>> 3

(set! a (- a 2))

a

>>> 1



Chicken Wiki - Unit Library

± a = 4

a

>>> 4

a--

a

>>> 3

a -= 2

a

>>> 1

± #include <stdio.h>



int main() {

int a = 8;

a -= 1;

printf("%d

", a);

}

>>> 7

±

Environment Variables

±

Comments and Docstrings

±

Task English Python Chicken Javascript C

Inline Comment

± Insert a line of text in the source code that is meant for human consumption and will not be processed by the programming language. Comments in English, unlike most programming languages, are

interpreted by the reader. Comments are most often shown in

parenthesis (though they can take other forms as well).















± # This is a comment

def test():

#print "hello"

return 35 + 7 # the answer to everything

test()

>>> 42

± ; This is a comment

(define (test)

;(print "hello")

(+ 35 7)) ;The answer to everything

(test)

>>> 42

± // This is a comment

function test() {

//document.write("hello")

return 35 + 7 // The answer to everything

}

test()

>>> 42

± Not all compilers support // comments. #include <stdio.h>



// This is a comment

int main() {

//printf("hello

");

int a = 35+7; // the answer to everything

printf("%d

", a);

}

>>> 42

±

Block Comment Syntax for multi-line comments. ± Insert a block of text in the source code that is meant for human consumption and will not be processed by the programming language. Comments in English are inherently multi-lined (You can continue

a comment until you use the closing parenthesis, though it is

better form to keep your comments short).







± # Python does not support block comments

#

# just separate paragraphs with one '#'



± You can also use multi-line strings as block comments

"""This is

a multi-line

comment"""

± #| This is a block comment



It might be better form not to use these. |#

Chicken Wiki - Non-standard Read Syntax

± /* This is a block comment



It might be better form not to use these. */

± Block comments cannot be nested. /* This is a block comment



Using block comments like this can cause confusion.*/

/*

* Instead you should include some

* sort of indication on each line

* of a comment to make long comments

* more readable.

*/

Recommended C Style and Coding Standards

±

Nested Comments

± Does the language support nested comments? (this is a comment [with a nested comment])











± # this is a comment # with a nested comment

± ; This is a comment ; with a nested comment

± // This is a comment // with a nested comment

± C does not allow nested block comments.

A workaround is to use the preprocessor ifdef command GCC Preprocessor

±

Docstrings A docstring is a comment on a segment of code that is retained during the runtime of a program. ±

Function and Class Docstrings

± Attach a string to a function or class that can later be retrieved through introspection tools.

± def add(x, y):

"""return result of X+Y



Docstrings are placed immediately after

function/class definitions and must use

triple quotes. Python style recommends

a one line description followed by a blank

line then a detailed description."""

return x+y

add(3, 8)

>>> 11

± Chicken does not support docstrings. ± Javascript does not support docstrings. ± Docstrings are not available in C. ±

Module Docstrings

± Attach a string to a module that can later be retrieved through introspection tools.





± Include a triple quoted string as the first non-comment line in a module. ± Chicken does not support docstrings. ± Javascript does not support docstrings. ± Docstrings are not available in C. ±

Retrieve Docstring

± Retrieve a docstring that has been attached to an object.





± > def test(x):

"""Print x



This documentation will show up

when you use help(test)"""

print x



help(test)

>>> Help on function test in module __main__:

>>>

>>> test(x)

>>> Print x

>>>

>>> This documentation will show up

>>> when you use help(test)

± Chicken does not support docstrings. ± Javascript does not support docstrings. ± Docstrings are not available in C. ±

Identity and Equality

±

Task English Python Chicken Javascript C

Identity

± An object or entity's identity is a source of intense philosophical debate. The full qualifying name of an object or entity is rarely unique and is usually resolved by context.



Human entities are often given a first, middle and last name as well as various identification numbers (Social Security Number or Driver's License Number in the US).



Non-human entities sharing residence with humans are often given first names such as Spot or Fido. Those not living with humans are often identified by family or species name.



Inanimate objects are often referred to by type or brand name and are usually qualified by ownership, such as "Jack's computer".

± a = "hello"

id(a)

>>> 136954848

± Add Entry for Chicken... Add Entry for Javascript... Add Entry for C...

Equivalence

± Given two references to objects, do the reference the exact same object? Given a list a comprised of the numbers 1 and 2 and a list b

comprised of the numbers 1 and 2 in the same order as a, the

values of a and b are equal. However both a and b are separate

and distinct lists.











± a = [1,2]

b = [1,2]

a == b

>>> True

a is b

>>> False

± (define a (list 1 2))

(define b (list 1 2))

(equal? a b)

>>> #t

(eqv? a b)

>>> #f

± a = [1, 2]

b = [1, 2]

a.toString() == b.toString()

>>> true

a === b

>>> false

± #include <stdio.h>

#include <string.h>



int main() {

char a[10] = "hello";

char b[10] = "hello";

int c = strcmp(a,b)

printf("%d

", c);

}

>>> 0



±

General Equality

± Given two objects do their values compare equal? Given a list a comprised of the numbers 1 and 2 and a list b

comprised of the numbers 1 and 2 in the same order as a, the

values of a and b are equal.







± a = [1,2]

b = [1,2]

a == b

>>> True

± (define a (list 1 2))

(define b (list 1 2))

(equal? a b)

>>> #t

± == will return false on two different arrays, even if their values are ===. One way to compare arrays for general equality is to convert each to a string then test for equality of the strings. a = [1, 2]

b = [1, 2]

a.toString() == b.toString()

>>> true

± Note that this is not an example of general equality, but it works on numbers. #include <stdio.h>



int main() {

int a = 3;

float b = 3.0;

int c = a == b;

printf("%d

", c);

}

>>> 1

±

Boolean Logic

±

Task English Python Chicken Javascript C

Convert to Boolean Convert an object to a boolean value (true or false) using standard equality. ± Convert an object to a boolean value (true or false) using standard equality. That which is not true is false.





± bool(42)

>>> True

bool([])

>>> False

Python Library Reference - Built-in Types

± (define (->bool object) (not (not object)))

(->bool 42)

>>> #t

(->bool '())

>>> #t

± !!42

>>> true

!![]

>>> true

± #include <stdio.h>



int toBool(arg) {

if (arg) {return 1;}

else {return 0;}

}



int main() {

int a = 42;

int b = toBool(a);

printf("%d

", b);

}

>>> 1

±

Boolean Operations

±

Any Return true if any argument evaluates to true. ± Return true if any argument evaluates to true. Return true if any element in a list evaluates to boolean true.

Stop evaluating after the first true value is reached.













± any([False, False, 3])

>>> True

any([False, False, False])

>>> False



Python Library Reference - Built-in Functions

± Any odd numbers?

any(x%2 for x in [1, 2, 3])

>>> True

any(x%2 for x in [2, 4, 6])

>>> False

± (use srfi-1)

(any (lambda (x) (if x #t #f)) (list #f #f 3))

>>> #t

(any (lambda (x) (if x #t #f)) (list #f #f #f))

>>> #f



SRFI-1

±

(use srfi-1)

(any odd? (list 1 2 3))

>>> #t

(any odd? (list 2 4 6))

>>> #f

± a = [false, false, 3]

b = [false, false, false]

function any(arr) {

for (ii in arr) {

if (!!arr[ii] == true) {return true}

}

return false}

any(a)

>>> true

any(b)

>>> false

± #include <stdio.h>



int any(int *array, int array_length) {

int count;

for (count = 0; count < array_length; count++) {

if (array[count]) {

return 1;

}

}

return 0;

}



int main ( ) {

int a[3] = {0, 0, 1};

int b[3] = {0, 0, 0};

printf("%i %i

", any(a, 3), any(b, 3));

}

>>> 1 0

±

All Return true if all arguments evaluate to true. ± Return true if all arguments evaluate to true. Return true if all elements in a list evaluate to true.





± all([1, 2, 3])

>>> True

all([1, False, 3])

>>> False



Python Library Reference - Built-in Functions

± All odd numbers?

all(x%2 for x in [1, 3, 5])

>>> True

all(x%2 for x in [1, 2, 3])

>>> False

± (use srfi-1)

(every (lambda (x) (if x #t #f)) (list 1 2 3))

>>> #t

(every (lambda (x) (if x #t #f)) (list 1 #f 3))

>>> #f



SRFI-1

±

(use srfi-1)

(every odd? (list 1 3 5))

>>> #t

(every odd? (list 1 2 3))

>>> #f

± a = [false, false, 3]

a.every(function (x) { return x; })

>>> true

a = [false, false, false]

a.every(function (x) { return x; })

>>> false

Blog

± #include <stdio.h>



int all(int *array, int array_length) {

int count;

for (count = 0; count < array_length; count++) {

if (!array[count]) {

return 0;

}

}

return 1;

}



int main ( ) {

int a[3] = {1, 2, 3};

int b[3] = {1, 2, 0};

printf("%i %i

", all(a, 3), all(b, 3));

}

>>> 1 0

±

Task English Python Chicken Javascript C

If

± If 1 is less than 2, print 'Yes' to the screen, otherwise print

'No' to the screen.



± If one is less than two, print 'yes' to the screen.





± if 1 < 2:

'Yes'

else:

'No'

>>> 'Yes'



±

if 1 < 2: 'Yes'

>>> 'Yes'

± The ;;else line is not required and is rarely, if ever, used. (if (< 1 2)

"Yes"

;;else

"No")

>>> "Yes"



±

(if (< 1 2) "Yes")

>>> "Yes"

± if (1 < 2) {

return 'yes'}

else {

return 'no'}

>>> yes

± #include <stdio.h>



int main() {

if (2 < 1) {

printf("Yes

");}

else {

printf("No

");}

}

>>> No



±

#include <stdio.h>



int main() {

if (1 < 2) {printf("Yes

");}

}

>>> Yes

±

Pattern Matching Pattern matching compares arguments by their structure. ±

Input and Output

±

Task English Python Chicken Javascript C

Expression Input Evaluate an expression given as input. ± Evaluate an expression given as input.

± a = 42

input()

a

>>> 42

input()

hello

>>> NameError: name 'hello' is not defined

± (define a 42)

(eval (read))

a

>>> 42

(eval (read))

hello

>>> Error: unbound variable: hello

± One way to get user input is using prompt(), then eval the string, though it's probably not a good idea to do this. Web Developers Notes

± Add Entry for C...

Printing Writing a string to standard output. ±

Print

± Print a string or string representation to standard out. Display the string "hello" on the screen.







± print 'hello'

>>> hello

± print both writes to std out and returns its argument. (print "hello")

>>> hello

>>> "hello"

± document.write("hello")

>>> hello

± #include <stdio.h>



int main() {

printf("hello

");

}

>>> hello

±

Task English Python Chicken Javascript C

Defining Functions

± Defining a new function. A function named someFunc that takes no arguments, returns no

value and prints "hello" to the screen when called.





± def someFunc():

print "Hello"

someFunc()

>>> "Hello"

± (define (someFunc)

(print "Hello"))

(someFunc)

>>> "Hello"

± function someFunc() {

return "hello"

}

someFunc()

>>> "hello"

± #include <stdio.h>



void someFunc() {

printf("Hello

");

}



int main() {

someFunc();

}

>>> Hello

±

Passing Arguments

± Syntax for passing arguments to functions. A function named someFunc that takes one argument, labeled a,

returns nothing and prints the value of a to the screen when

called.





± def someFunc(a):

print a

someFunc("Hello World")

>>> Hello World

± (define (someFunc a)

(print a))

(someFunc "Hello World")

>>> Hello World

± function someFunc(a) {

document.write(a)

}

someFunc("Hello")

>>> Hello

± #include <stdio.h>



void someFunc(char * a) {

printf("%s

", a);

}



int main() {

someFunc("Hello World");

}

>>> Hello World

±

Returning Values

± Syntax for returning values from functions. A function named someFunc that takes one argument, labeled a,

and returns the value of a when called.





± def someFunc(a):

return a

v = someFunc(42)

v

>>> 42

± 888 (define (someFunc a)

a)

(define v (someFunc 42))

v

>>> 42



± function someFunc(a) {

return a

}

v = someFunc(42)

v

>>> 42

± #include <stdio.h>



int someFunc(a) {

return a;

}



int main() {

int b = someFunc(42);

printf("%d

", b);

}

>>> 42

±

Calling Functions

± Syntax for calling a function.

± def add(x, y):

return x + y

add(35, 7)

>>> 42

add(35, -42)

>>> -7

± (define (add x y)

(+ x y))

(add 35 7)

>>> 42

(add 35 -42)

>>> -7

± function add(x, y) {

return x + y

}

add(35, 7)

>>> 42

add(35, -42

>>> -7

± #include <stdio.h>



void add(a, b) {

int c = a + b;

printf("%d

", c);

}



int main() {

add(35, 7);

add(35, -42);

}

>>> 42

>>> -7

±

Evaluation Order

± The order of evaluation for arguments to a function.

± Left to right. def p(a): print a

def test(a,b,c,d):

return 3 + -10

test(p(1), p(2), p(3), p(4))

>>> 1

>>> 2

>>> 3

>>> 4

>>> -7

Python Library Reference - Expressions

± Unspecified (define (test a b c d)

(+ 3 -10))

(test (print "1") (print "2") (print "3") (print "4"))

>>> 1

>>> 2

>>> 3

>>> 4

>>> -7

± Left to right.

This example has to be a bit different than the others as Javascript does not have a function to print to stdout. function p(a) {document.write(a)}

function t(a, b, c, d) {

document.write(7)

}

t(p(1), p(2), p(3), p(4))

>>> 12347

± #include <stdio.h>



int p(a) {

printf("%d

", a);

}



int test(a, b, c, d) {

return 1;

}



int main() {

test(p(1), p(2), p(3), p(4));

}

>>> 4

>>> 3

>>> 2

>>> 1

±

Argument Binding Early or late binding. ± If the default value of a function argument is assigned as a random number, when is the random number bound to the argument. If it is bound at definition (early binding) it will return the same number every time it is called. If it is bound at run-time (late binding) it will be a different, random number every time it is called.









± Arguments are bound at definition, therefore this function will always return 42. import random

def r(a=random.randrange(1, 100)):

return a

r()

>>> 42

r()

>>> 42

r()

>>> 42

± Arguments are bound at runtime, therefore this function will return a random number. (define (r #!optional (a (random 100)))

a)

(r)

>>> 35

(r)

>>> 92

(r)

>>> 58

± Late binding

Javascript does not support optional arguments with default values. Because of this the examples from other languages to test late vs early binding will not work. stackoverflow

± Add Entry for C...

All Arguments Must Be Supplied? If you specify a number of arguments to a function must you call that function with the exact number of arguments? ± If the number of arguments to a function is specified at the time of definition, is it an error to call that function with more or less arguments than specified?





± def testArgs(a, b, c):

print "Successful"

testArgs(1, 2)

>>> TypeError: testArgs() takes exactly 3 arguments (2 given)

± (define (testArgs a b c)

(print "Successful"))

(testArgs 1 2)

>>> Error: Bad argument count - received 2 but expected 3

± No unspecified arguments are set to undefined. function testArgs(a, b, c) {

return "Successful"

}

testArgs(1, 2)

>>> "Successful"

stackoverflow

± #include <stdio.h>



void testArgs(a, b, c) {

printf("Successful

");

}



int main() {

testArgs(1, 2);

}

>>> Successful

±

Arbitrary Number of Keyword Arguments

± Pass an arbitrary number of unknown key-value arguments to the function. Usually the unknown arguments are passed to the function body as a hash table.

± def keyArgs(a, **kwargs):

return [a, kwargs]

keyArgs(1)

>>> [1, {}]

keyArgs(1, y=2, z=3)

>>> [1, {'z':3, 'y':2}]

± #!rest could be used here but it would need some additional logic to associate keys and values. ± Javascript does not directly support keyword arguments. ± Add Entry for C...

Are arguments passed by value or reference?

± When a complex data type is passed as an argument to a function is the value of that data type passed or is a reference to the structure passed?



For instance, if 'a' equals a list (1, 2, 3) and we pass 'a' as an argument to a function. If the first element in 'a' is set to 42 within the function body, is the change reflected in 'a' outside the function body? If it is, 'a' was passed by reference and if not, 'a' was passed by value.

± Add Entry for Python... Add Entry for Chicken... Add Entry for Javascript... Add Entry for C...

Anonymous, Nested and Curried Functions

±

Task English Python Chicken Javascript C

Creating a Module

±

Errors and Exceptions

±

Task English Python Chicken Javascript C

Example Error

± "This sentence is false."

The above sentence results in a logical error known as the liar's paradox.



An error or exception is a special condition in a computer program. In some languages errors can be tested for and used as a branching mechanism. In other languages errors will cause segmentation faults or otherwise fail, sometimes silently.





± 1+'a'

>>> Traceback (most recent call last):

>>> File "<stdin>", line 1, in <module>

>>> TypeError: unsupported operand type(s) for +: 'int' and 'str'

± (+ 1 "a")

>>> Error: (+) bad argument type: "a"

>>>

>>> Call history:

>>>

>>> <eval> (+ 1 "a") <--

± a

>>> ReferenceError: a is not defined

± Exception Handling in C without C++

±

Default Exceptions

± A programming language that handles exceptions will usually provide a base set of exceptions. This set usually encompasses common errors with native types. In many languages you are allowed to extend the set of exceptions to include your own custom exceptions.





± Exception Base Classes:

BaseException, Exception, StandardError, ArithmeticError, LookupError, EnvironmentError



Built-in Exceptions:

AssertionError, AttributeError, EOFError, FloatingPointError, GeneratorExit, IOError, ImportError, IndexError, KeyError, KeyboardInterrupt, MemoryError, NameError, NotImplementedError, OSError, OverflowError, ReferenceError, RuntimeError, StopIteration, SyntaxError, SystemError, SystemExit, TypeError, UnboundLocalError, UnicodeError, UnicodeEncodeError, UnicodeDecodeError, UnicodeTranslateError, ValueError, VMSError, WindowsError, ZeroDivisionError



Warnings:

Warning, UserWarning, DeprecationWarning, PendingDeprecationWarning, SyntaxWarning, RuntimeWarning, FutureWarning, ImportWarning, UnicodeWarning Python Library Reference - Built-in Exceptions

± arity, type, arithmetic, i/o, i/o file, i/o net, bounds, runtime, runtime limit, match, syntax, breakpoint ± Javascript has 2 basic types of errors: Syntax and Runtime. mediacollege.com

± C does not provide native exception handling.

±

Catching Errors

±

Catch Any Exception

± Generally an exception will terminate the normal flow of a program. If the language provides an exception handling mechanism how does one run code that might throw an arbitrary exception, and handle that exception upon its occurrence?





± def add(x, y):

try:

return x+y

except:

return 'Error'

add(3, 4)

>>> 7

add('3', 'a')

>>> Error

± (define (add x y)

(condition-case (+ x y)

((exn) 'Error)))

(add 3 4)

>>> 7

(add "3" "a")

>>> 'Error

Chicken Wiki - Unit library

± function add(x, y) {

try {

return y + abc

}

catch(err) {

return 'error'

}

}

add(3, 4)

>>> "error"

± C does not provide native exception handling.

±

Try Allows Multiple Expressions?

± Does the exception handling mechanism (usually invoked using the try keyword) allow multiple expressions to be "tried"?

± a = 0

b = 0

try:

a += 1

b = 5

except:

False

a

>>> 1

b

>>> 5

± (define a 0)

(define b 0)

(condition-case

(begin

(set! a (+ a 1))

(set! b 5))

((exn) 'False))

a

>>> 1

b

>>> 5

± a = 0

b = 0

try {

a += 1

b = 5

}

catch(err) {

false

}

a

>>> 1

b

>>> 5

± C does not provide native exception handling.

±

Throwing Errors

±

Task English Python Chicken Javascript C

Overview

± An overview of looping techniques.

± Python has a number of looping constructs.



The most common methods of looping in Python are the for loop, the while loop and comprehensions.



Python supports recursion as a form of looping, but beware that there is usually a recursion depth limit set at 1,000. This can be changed, but ultimately Python will run out of stack space as it is not properly tail recursive.



Python also offers map, filter and reduce.

± Chicken, like all compliant Schemes, is properly tail-recursive. Recursion is a standard and encouraged practice for looping.



Chicken also offers a do loop and writing custom for and while loop constructs is trivial. Eager comprehensions are available through the SRFI-42 library.

± Add Entry for Javascript... The for and while loops are most prominent in C.

±

Support for Tail-Call Optimization? Will the language properly transform tail recursive functions into iterative ones? ± Will the language properly transform tail recursive functions into iterative ones?

± No def recursiveFunction(x):

if x > 500000:

print x

else:

print x

recursiveFunction(x+1)

recursiveFunction(1)

>>> 1

>>> ...

>>> 999

>>> RuntimeError: maximum recursion depth exceeded

± Yes, TCO is required for compliance with the Scheme standard. ± No ± No #include <stdio.h>



int recursiveFunction(x) {

if (x > 500000) {

printf("%d

", x);}

else {

printf("%d

", x);

recursiveFunction(x+1);}

}



int main() {

recursiveFunction(1);

}

>>> 1

>>> ...

>>> 261932

>>> Segmentation fault

±

Are Recursive Functions Supported?

± Are recursive functions supported?

± Yes def recursiveFunction(x):

if x == 3:

print x

else:

print x

recursiveFunction(x+1)

recursiveFunction(1)

>>> 1

>>> 2

>>> 3

± Yes, recursion and TCO are part of the Scheme standard (define (recursiveFunction x)

(if (= x 3)

(print x)

(begin

(print x)

(recursiveFunction (+ x 1)))))

(recursiveFunction 1)

>>> 1

>>> 2

>>> 3

± Yes function recursiveFunction(x) {

if (x == 3) {

return x}

else {

recursiveFunction(x+1)}

}

recursiveFunction(1);

>>> 3

± Yes #include <stdio.h>



int recursiveFunction(x) {

if (x == 3) {

printf("%d

", x);}

else {

printf("%d

", x);

recursiveFunction(x+1);}

}



int main() {

recursiveFunction(1);

}

>>> 1

>>> 2

>>> 3

±

Task English Python Chicken Javascript C

Comprehensions Part of the Core Language?

± Are comprehensions part of the core language and is it idiomatic to use them?

± Yes ± No

SRFI-42 is not installed by default, to install it use the chicken-install program from the command line:

$ sudo chicken-install srfi-42 ± No but Python-like comprehensions are making their way into Javascript. Mozilla

± No ±

List Comprehensions

±

Conditional Comprehensions Iterate over each item in a sequence, if it satisfies a condition, perform an operation with that item and accumulate the results in a list. ± Iterate over each item in a sequence, if it satisfies a condition, perform an operation with that item and accumulate the results in a list. Conditional comprehensions can be either lazy or eager depending upon language and implementation.

± [ii for ii in range(10) if x % 2 == 0]

>>> [0, 2, 4, 6, 8]

words = ['hi', 'hello', 'bye', 'cya', 'goodbye']

[word for word in words if len(word) <= 3]

>>> ['hi', 'bye', 'cya']

Python: List Comprehensions

± (use srfi-42)

(list-ec (: ii 10) (if (even? ii)) ii)

>>> (0 2 4 6 8)

(define words '("hi" "hello" "bye" "cya" "goodbye"))

(list-ec (: ii words) (if (< (string-length ii) 4)) ii)

>>> ("hi" "bye" "cya")

± N/A ± Comprehensions are not part of the core language.

±

Nested Comprehensions

± Can you nest comprehensions?

± [[(x,y) for y in range(2)] for x in range(3)]

>>> [[(0, 0), (0, 1)], [(1, 0), (1, 1)], [(2, 0), (2, 1)]]

± (list-ec (: x 3) (list-ec (: y 2) (list x y)))

>>> (((0 0) (0 1)) ((1 0) (1 1)) ((2 0) (2 1)))

± N/A ± Comprehensions are not part of the core language.

±

Vector Comprehensions

±

Vector Comprehensions

± Iterate over each item in a sequence performing an operation with that item and accumulating the result in a vector. Vector comprehensions can be either lazy or eager depending upon language and implementation.

± Add Entry for Python... (vector-ec (: ii 3) ii)

>>> #(0 1 2)

± N/A ± Comprehensions are not part of the core language.

±

String Comprehensions

±

String Comprehensions

± Iterate over each item in a sequence performing an operation with that item and accumulating the result in a string. String comprehensions can be either lazy or eager depending upon language and implementation.

± Add Entry for Python... (string-append-ec (: ii 3) ii)

>>> "123"

(string-ec (: ii '(#\a #\b #\c)) ii)

>>> "abc"

± N/A ± Comprehensions are not part of the core language.

±

Hash Table Comprehensions

±

Task English Python Chicken Javascript C

Find Type of Object

± Get the type of an object.

± a = 42

type(a)

>>> <type 'int'>

b = 'hello'

type(b)

>>> <type 'str'>

± (define (type s)

(cond

((boolean? s) 'boolean)

((symbol? s) 'symbol)

((char? s) 'char)

((vector? s) 'vector)

((null? s) 'null)

((pair? s) 'pair)

((number? s) 'number)

((string? s) 'string)

((procedure? s) 'procedure)))

(type 42)

>>> number

(type "hello")

>>> string

(type 's)

>>> symbol

± a = 42

typeof a

>>> "number"

± This is not possible in C. bytes.com

±

Numeric Types

±

Sequence Types

±

Array or Vector

± A type suitable for representing a contiguous block of memory reserved for elements accessible via index.

± a = [1, 2, 3]

type(a)

>>> <type 'list'>

b = list((1, 2, 3))

type(b)

>>> <type 'list'>

± (define a (vector 1 2 3))

(vector? a)

>>> #t

a

>>> #(1 2 3)

± a = [1, 2, 3]

a

>>> [1, 2, 3]

b = Array(1, 2, 3)

b

>>> [1, 2, 3]

± #include <stdio.h>



int main() {

int a[3] = {1, 2, 3};

int b[] = {1, 2, 3};

}

±

String

± A type suitable for representing an array or list of characters.

± a = "abc"

type(a)

>>> <type 'str'>

b = str(42)

type(b)

>>> <type 'str'>

± (define a "abc")

(string? a)

>>> #t

± a = "hello"

typeof a

>>> "string"

b = String(42)

typeof b

>>> "string"

± C doesn't really have 'strings' instead they are arrays of characters. If you specify the length explicitly, remember to add an extra character for the termination character. #include <stdio.h>



int main() {

char a[4] = "abc";

char b[] = "xyz";

printf("%s %s

", a, b);

}

±

Other Types

±

Character

± A type suitable for representing a single character, encoding not specified.

± Python does not have a character type, just use the string type. a = "c"

type(a)

>>> <type 'str'>

± (define a #\c)

(char? a)

>>> #t

± Javascript does not have a character type. Use a string with a single character. ± char a = 'c';

±

OS Integration

±

Task English Python Chicken Javascript C

Working with the Language

±

Shell Access, Processes and Forking

±

Working with the Filesystem

±

Task English Python Chicken Javascript C

Task English Python Chicken Javascript C

Interfacing with C

±

Task English Python Chicken Javascript C

Data Structures Strings, lists, arrays, vectors, hash maps and more... ±

Strings A string is an ordered sequence of letters, numbers and/or symbols. ±

Task English Python Chicken Javascript C

The Empty String

± Representation of the empty string.

± ""

>>> ""

± ""

>>> ""

± ""

>>> ""

± C does not have a built-in string type, instead it uses null terminated arrays. There are a few ways you could check if a string is empty. The best seems to be: if ( (s == NULL) || (*s == 0) )

Forum

±

Conversion Converting a string into another type, or another type into a string. ±

String To Integer

± Convert a string to an integer.





± a = "42"

b = int(a)

b

>>> 42

type(b)

>>> <type 'int'>

± (define a "42")

(define b (string->number a))

b

>>> 42

(integer? b)

>>> #t

± a = Number("42")

typeof a

>>> "number"

± #include <stdio.h>

#include <stdlib.h>



int main()

{

char a[] = "42";

int b = atoi(a);

printf("%d

", b);

}

>>> 42

codeguru - forums

±

Characters To String Convert a sequence of characters to a string. ± Convert a sequence of characters to a string.

± Python does not have a character type. ''.join(['h', 'e', 'l', 'l', 'o'])

>>> 'hello'

± (string #\h #\e #\l #\l #\o)

>>> "hello"

R5RS

± ['h', 'e', 'l', 'l', 'o'].join("")

>>> "hello"

± A string is an array of characters with '\0' as the last character. ±

String To Characters Convert a string to a sequence of characters. ± Convert a string to a sequence of characters.

± [ii for ii in 'hello']

>>> ['h', 'e', 'l', 'l', 'o']

± (string->list "hello")

>>> (#\h #\e #\l #\l #\o)

± "hello".split("")

>>> ["h", "e", "l", "l", "o"]

± A string is an array of characters with '\0' as the last character ±

Indexing, Splitting and Joining

±

Character Indexing Obtaining a single character from a string by its position. ± Obtaining a single character from a string by its position.

± "Sample"[1]

>>> 'a'

"Sample"[-1]

>>> 'e'

± The next entry has a version of string-ref that supports negative indexing (string-ref "Sample" 1)

>>> #\a

(string-ref "Sample" -1)

>>> Error: (string-ref) out of range



R5RS

±

(define (neg-string-ref aString index)

(if (< index 0)

(string-ref aString (+ (string-length aString) index))

(string-ref aString index)))

(neg-string-ref "Sample" -1)

>>> #\e



± a = "Sample"

a[1]

>>> a

± #include <stdio.h>



int main() {

char aString[] = "Sample";

char a = aString[1];

printf("%c

", a);

}

>>> a

Cprogramming - Message Boards

±

Substring (Slice) Get a portion of the string. ± Get a portion of the string from a starting value to an ending value.

± "Sample"[1:3]

>>> 'am'

"Sample"[-2:]

>>> 'le'

± Python's behavior can be emulated by writing a new function 'pysubstring' that simply subtracts the negative numbers from the length of the string to get the index. (substring "Sample" 1 3)

>>> "am"

(substring "Sample" -2 -1)

>>> Error: (substring) index out of bounds

R5RS

Drinkable Chicken

± a = "Sample";

a.substring(1, 3)

>>> am



±

a = "Sample"

a.substr(1, 3)

>>> amp

± devshed - forums

±

Split String At Line Breaks

± Split a string at each occurrence of a line break.

± """just a

multi lined

string""".splitlines()

>>> ['just a', 'multi lined', 'string']

± (define a "just a

multi lined

string")

(string-split a "

")

>>> ("just a" "multi lined" "string")

± splitString = new Array()

splitString = 'just

a

multilined

string'.split(" ")

splitString

>>> ["a", "sample", "string"]

± Add Entry for C...

Concatenation Adding two or more Strings together end-to-end. ± Join two or more strings together end to end to form one string.

± "Hello" + " " + "World"

>>> "Hello World"

"".join('Hello', 'World')

>>> "Hello World"

± (conc "Hello" " " "World")

>>> "Hello World"

(string-append "Hello" " " "World")

>>> "Hello World"

R5RS

± a = "Hello" + " " + "World"

a

>>> "Hello World"

± #include <stdio.h>

#include <string.h>



int main() {

char a[25] = "Hello ";

char b[25] = "World!

";

strcat(a, b);

printf("%s", a);

}

>>> Hello World!

Strings in C

±

String Case Operations that deal with the case of strings. ±

Searching And Replacing

±

Change Character At Index! Destructively modify a character in the string. ± Destructively modify a character in the string.

± Strings are immutable so any example of this will likely only be an emulation. def stringSet(aString, n, val):

s = [ii for ii in aString]

s[n] = val

return ''.join(s)

aString = "hello"

aString = stringSet(aString, 1, "a")

aString

>>> 'hallo'

± This is usually considered bad style (define a "hello")

(string-set! a 1 #\a)

a

>>> "hallo"

R5RS

± Add Entry for Javascript... Add Entry for C...

Copy

± Copy a string, returning a new string of the same value.

± Strings are immutable, therefore copying them in the standard way results to a reference to the 'same' string. This method creates a 'new' (id) string. Note some strings will always have the same identity (like the empty string). a = 'hello'

b = ''.join(a)

a == b

>>> True

a is b

>>> False

c = ''.join(a[1:3])

c

>>> 'el'

± (define a "hello")

(define b (string-copy a))

(equal? a b)

>>> #t

(eqv? a b)

>>> #f

(define c (string-copy a 1 3))

c

>>> "el"

± Add Entry for Javascript... #include <stdio.h>

#include <string.h>



int main() {

char a[] = "Hello";

char *b = strdup(a);

printf("%s

%s

", a, b);

return 0;

}



±

More Documentation

±

Linked Lists

±

Task English Python Chicken Javascript C

List Functions

±

Slice or Sublist

± Return a sublist of a list given a starting and ending index.

± testList = [1, 2, 3, 4, 5, 6, 7, 8, 9]

testList[3:6]

>>> [4, 5, 6]

testList[:3]

>>> [1, 2, 3]

testList[6:]

>>> [7, 8, 9]

testList[-3:]

>>> [7, 8, 9]



±

def schemeSlice(aList, start, sliceLength):

return aList[start:start+sliceLength]

testList = [1, 2, 3, 4, 5, 6, 7, 8, 9]

schemeSlice(testList, 2, 3)

>>> [3, 4, 5]

± Even with srfi-1 there doesn't seem to be a built-in method of obtaining a sublist from a list. However the two functions defined here (slice and pyslice) should be a good start. (use srfi-1)

(define testList (list 1 2 3 4 5 6 7 8 9))

(define (slice aList start sliceLength)

(take (drop aList start) sliceLength))

(slice testList 3 3)

>>> (4 5 6)



± The pyslice function could easily be extended to provide colon notation like Python.

(use srfi-1)

(define (slice aList start sliceLength)

(take (drop aList start) sliceLength))

(define (pyslice l start stop)

(slice l start (- stop start)))

(define testList (list 1 2 3 4 5 6 7 8 9))

(pyslice testList 3 6)

(4 5 6)

± Add Entry for Javascript... Add Entry for C...

Append Element to List

± Append a single value to a list, returning a new list.





± a = [1, 2, 3]

b = a + [4]

a

>>> [1, 2, 3]

b

>>> [1, 2, 3, 4]

c = a + [[4, 5]]

c

>>> [1, 2, 3, [4, 5]]

± (define (append-element aList element)

(append aList (list element)))

(define a (list 1 2 3))

(define b (append-element a 4))

a

>>> (1 2 3)

b

>>> (1 2 3 4)

(define c (append-element a (list 4 5)))

c

>>> (1 2 3 (4 5))

± Add Entry for Javascript... Add Entry for C...

Remove by Value!

± Remove the first occurrence of a value from a list.

± a = [1, 2, 3, 4, 5]

a.remove(1)

a

>>> [2, 3, 4, 5]

a.remove(5)

a

>>> [2, 3, 4]

± Note: remove-by-value! will produce an error if given a list of length 1. (define (remove-by-value! aList value)

(if (equal? (car aList) value)

(begin

(set-car! aList (cadr aList))

(set-cdr! aList (cddr aList)))

;else

(if (equal? (cadr aList) value)

(set-cdr! aList (cddr aList))

(remove-by-value! (cdr aList) value))))

(define a '(1 2 3 4 5))

(remove-by-value! a 1)

a

>>> (2 3 4 5)

(remove-by-value! a 5)

a

>>> (2 3 4)



± delete! removes all occurrences of a value from a list

Note: srfi-1's delete! will remove the value from the original list, except when the value is the first element in that list. See examples below.

(use srfi-1)

(define a '(1 2 3 4 5))

(delete! 3 a)

>>> (1 2 4 5)

a

>>> (1 2 4 5)

(delete! 1 a)

>>> (2 4 5)

a

>>> (1 2 4 5)

SRFI-1

± Add Entry for Javascript... Add Entry for C...

Is Value in List? (Return Rest of List)

± Search for a given value in a list and return the rest of the list from the first occurrence of that value onward if the value is present.

± def findTailByValue(aList, value):

return aList[aList.index(value):]

a = [1, 2, 3, 4, 5]

findTailByValue(a, 3)

>>> [3, 4, 5]

findTailByValue(a, 'z')

>>> ValueError: list.index(x): x not in list

± (define a '(1 2 3 4 5))

(member 3 a)

>>> (3 4 5)

(member "xyz" a)

>>> #f

± Add Entry for Javascript... Add Entry for C...

Arrays and Vectors

±

Task English Python Chicken Javascript C

Overview

± A type suitable for representing a contiguous block of memory reserved for elements accessible via index.

± Python's list data type is similar to vectors or arrays in most other languages, and is what we will use here.

EDIT: Should we take the opportunity to illustrate Python's tuple data structure here? The only downside is that it is immutable so a few concepts here wouldn't apply. ± Scheme's vector data type is comparable to arrays in other languages.

Some examples here will use vector-lib which is not installed by default. To install it use chicken-install from the shell as outlined below:

$ sudo chicken-install vector-lib ± Add Entry for Javascript... Add Entry for C...

The Empty Array

± Notation for an empty array.

± a = []

a

>>> []

± (define a (vector))

a

>>> #()



±

(define c (make-vector 0))

c

>>> #()

± a = []

a

>>> []

± int a[0];

±

Does the Empty Array Equal False?

± Does the empty array equal false? Is this true of conditionals as well?

± a = []

a == False

>>> False

not a

>>> True

± (equal? (vector) #f)

>>> #f

(not (vector))

>>> #f

± a = []

a == false

>>> true

!!a

>>> true

± #include <stdio.h>



int main() {

int a[0];

if (a) {printf("True

");}

else {printf("False

");}

}

>>> True

±

Creating a Populated Array

± Representation of a populated array.

± a = [1, 2, 3]

a

>>> [1, 2, 3]

± (define a (vector 1 2 3))

a

>>> #(1 2 3)

(make-vector 3 7)

>>> #(7 7 7)

± a = [1, 2, 3]

a

>>> [1, 2, 3]

± #include <stdio.h>



int main() {

int a[3] = {1, 2, 3};

/* Print array */

int ii;

for (ii=0; ii < 3; ii++) {

printf("%d ", a[ii]);}

printf("

");

}

>>> 1 2 3

±

General Functions

±

First

± Return the first value in a given array.

± a = [1, 2, 3]

a[0]

>>> 1

± (define a (vector 1 2 3))

(vector-ref a 0)

>>> 1

± a = [1, 2, 3]

a[0]

>>> 1

± #include <stdio.h>



int main() {

int a[3] = {1, 2, 3};

int first = a[0];

printf("%d

", first);

}

>>> 1

±

Rest

± Return an array of all of the values in a given array except for the first.

± a = [1, 2, 3]

a[1:]

>>> [2, 3]

± (use vector-lib)

(define a (vector 1 2 3))

(vector-copy a 1 (vector-length a))

>>> #(2 3)

± a = [1,2,3]

a.slice(1,a.length)

>>> [2, 3]

± Add Entry for C...

Length

± Get the count of values in an array.

± a = [1, 2, 3]

len(a)

>>> 3

± (define a (vector 1 2 3))

(vector-length a)

>>> 3

± a = [1, 2, 3]

a.length

>>> 3

± #include <stdio.h>



int main() {

int a[3] = {1, 2, 3};

int size = sizeof a / sizeof a[0];

printf("%d

", size);

}

>>> 3

±

Make an Array of Integers

± Create and return an array of integers.

± range(start, stop, step) range(5)

>>> [0, 1, 2, 3, 4]

range(0, 10, 2)

>>> [0, 2, 4, 6, 8]

± (define (vector-range number)

(let loop ((v (make-vector number)) (n 0))

(if (= n number)

v

;else

(begin (vector-set! v n n)

(loop v (+ n 1))))))

(vector-range 3)

>>> #(0 1 2)

± function range(start, stop, step) {

var a = []

if (step == undefined) {step = 1}

for (var i=start; i<stop; i+=step) {

a.push(i)

}

return a

}

range(0, 5)

>>> [0, 1, 2, 3, 4]

range(0, 10, 2)

>>> [0, 2, 4, 6, 8]

± Add Entry for C...

Index

± Return the value in an array at the location of a given index.

± a = [1, 2, 3, 4, 5, 6]

a[0]

>>> 1

a[3]

>>> 4

± (define a (vector 1 2 3 4 5 6))

(vector-ref a 0)

>>> 1

(vector-ref a 3)

>>> 4

± a = [1, 2, 3, 4, 5, 6]

a[0]

>>> 1

a[3]

>>> 4

± #include <stdio.h>



int main() {

int a[3] = {1, 2, 3};

int b = a[0];

int c = a[2];

printf("%d, %d

", b, c);

}

>>> 1, 3

±

Slice or Sublist

± Return a new array that is a subset of the values in the original array.

± testList = [1, 2, 3, 4, 5, 6, 7, 8, 9]

testList[3:6]

>>> [4, 5, 6]

testList[:3]

>>> [1, 2, 3]

testList[6:]

>>> [7, 8, 9]

testList[-3:]

>>> [7, 8, 9]

± (use vector-lib)

(define a (vector 1 2 3 4 5 6 7 8 9))

(vector-copy a 3 6)

>>> #(4 5 6)

(vector-copy a 0 3)

>>> #(1 2 3)

(vector-copy a 6 (vector-length a))

>>> #(7 8 9)

(vector-copy a (- (vector-length a) 3) (vector-length a))

>>> #(7 8 9)

± testList = [1, 2, 3, 4, 5, 6, 7, 8, 9]

testList.slice(3, 6)

>>> [4, 5, 6]

testList.slice(0, 3)

>>> [1, 2, 3]

testList.slice(6, testList.length)

>>> [7, 8, 9]

± Add Entry for C...

Append Array to Array

± Join two arrays to create a new array.

± a = [1, 2]

b = [3,4]

a+b

>>> [1, 2, 3, 4]

a

>>> [1, 2]

b

>>> [3, 4]

± (use vector-lib)

(define a (vector 1 2 3))

(define b (vector 4 5 6))

(vector-append a b)

>>> #(1 2 3 4 5 6)

a

>>> #(1 2 3)

b

>>> #(4 5 6)

± a = [1, 2]

b = [3, 4]

a.concat(b)

>>> [1, 2, 3, 4]

a

>>> [1, 2]

b

>>> [3, 4]

± Add Entry for C...

Join Arrays (Concatenate)

± Return a new array as the result of joining two given arrays.

± ['a', 'b'] + ['c'] + ['d', 'e']

>>> ['a', 'b', 'c', 'd', 'e']

['a', 'b'] + ['c'] + [['d'], ['e']]

>>> ['a', 'b', 'c', ['d'], ['e']]

± (use vector-lib)

(define a (vector 1 2))

(define b (vector 3 4))

(define c (vector 5 6))

(vector-concatenate (list a b c))

>>> #(1 2 3 4 5 6)

± ['a', 'b'].concat(['c']).concat(['d', 'e'])

>>> ['a', 'b', 'c', 'd', 'e']

± Add Entry for C...

Set Value at Index!

± Set the value of the element referenced by the given index, modifying the original array.





± a = [1, 2, 3, 4, 5]

a[3] = "abc"

a

>>> [1, 2, 3, 'abc', 5]

± (define a (vector 1 2 3 4 5))

(vector-set! a 3 "abc")

a

>>> #(1 2 3 "abc" 5)

± a = [1, 2, 3, 4, 5]

a[3] = "abc"

a

>>> [1, 2, 3, 'abc', 5]

± #include <stdio.h>



int main() {

int a[5] = {1, 2, 3, 4, 5};

a[1] = 777;

// Print array

int ii;

for (ii=0; ii < 5; ii++) {

printf("%d ", a[ii]);}

printf("

");

}

>>> 1 777 3 4 5

±

Reverse Array

± Reverse the order of the values in an array.

± Reverse the original list in place. a = [1, 2, 3]

a.reverse()

a

>>> [3, 2, 1]

± Reverse a vector in-place. (use vector-lib)

(define a (vector 1 2 3))

(vector-reverse! a)

a

>>> #(3 2 1)

± Reverse the original list in place. a = [1, 2, 3]

a.reverse()

a

>>> [3, 2, 1]

± Add Entry for C...

Index by Value

± Return the index of the first occurrence of a given value in an array.

± a = [1, 2, 3, 4, 5]

a.index(3)

>>> 2

a.index('xyz')

>>> ValueError: list.index(x): x not in list

± (use vector-lib)

(define a (vector 1 2 3 4 5))

(vector-index (lambda (x) (equal? x 3)) a)

>>> 2

(vector-index (lambda (x) (equal? x "abc")) a)

>>> #f

SRFI-43

± a = [1, 2, 3, 4, 5]

a.indexOf(3)

>>> 2

a.indexOf('xyz')

>>> -1

± Add Entry for C...

Is Value in Array? (Return Rest of Array)

± Search for a given value in an array and return the rest of the array from the first occurrence of that value onward if the value is present.





± def findTailByValue(aList, value):

return aList[aList.index(value):]

a = [1, 2, 3, 4, 5]

findTailByValue(a, 3)

>>> [3, 4, 5]

findTailByValue(a, 'z')

>>> ValueError: list.index(x): x not in list

± Add Entry for Chicken... a = ['a', 'b', 'c', 'b']

a.slice(a.indexOf('b'), a.length)

>>> ["b", "c", "b"]

± Add Entry for C...

Copy

± Create a shallow copy of an array.

± import copy

a = [1, 2, 3]

b = a

b is a

>>> True

c = copy.copy(a)

c is a

>>> False

± (define a (vector 1 2 3))

(define b (make-vector (vector-length a)))

(vector-copy! a b)

b

>>> #(1 2 3)

(equal? a b)

>>> #t

(eqv? a b)

>>> #f

± a = [1, 2, 3]

b = a

a == b

>>> true

c = a.slice()

c == a

>>> false

± Add Entry for C...

String to Array

± Convert a string to an array.

± [ii for ii in 'abc']

>>> ['a', 'b', 'c']

± (define (string->vector string)

(list->vector (string->list string)))

(string->vector "abc")

>>> #(#\a #\b #\c)

± "abc".split("")

>>> ["a", "b", "c"]

± "Strings" in C are arrays of characters, therefore they need no conversion. ±

Array to String

± Convert an array to a string representation.

± ''.join(['a', 'b', 'c'])

>>> 'abc'

± (define (vector->string vec)

(list->string (vector->list vec)))

(define a (vector #\a #\b #\c))

(vector->string a)

>>> "abc"

± a = ['a', 'b', 'c']

a.join("")

>>> "abc"

± "Strings" in C are arrays of characters, therefore they need no conversion.</c>

±

Linked List to Array

± Convert a linked list to an array.

± In this case we're going to demonstrate Python's tuple data-structure. a = [1, 2, 3]

tuple(a)

>>> (1, 2, 3)

± (define a (list 1 2 3))

(list->vector a)

>>> #(1 2 3)

± N/A ± Add Entry for C...

Array to Linked List

± Convert an array to a linked list.

± In this case we're going to demonstrate Python's tuple data-structure. a = (1, 2, 3)

list(a)

>>> [1, 2, 3]

± (define a (vector 1 2 3))

(vector->list a)

>>> (1 2 3)

± N/A ± Add Entry for C...

Hash Tables, Hash Maps and Dictionaries

±

Task English Python Chicken Javascript C

Hash Table Functions

±

Inserting and Removing

±

Modifying and Accessing

±

Keys and Values

±

Task English Python Chicken Javascript C

Inserting and Deleting

±

Set Functions

±

Stacks and Queues

±

Task English Python Chicken Javascript C

Trees and Graphs

±

Task English Python Chicken Javascript C

Task English Python Chicken Javascript C

Data Persistence

±

Task English Python Chicken Javascript C

Task English Python Chicken Javascript C

DBM dbm and its successors are database engines that allow data retrieval by key. ±

Task English Python Chicken Javascript C

Task English Python Chicken Javascript C

Time and Date

±

Task English Python Chicken Javascript C

Task English Python Chicken Javascript C

Random List Choice (Shallow) Return a random element of a list. This function is 'shallow' meaning that if a list is an element of the given list it will return that list (see examples). ± Return a random element of a list. This function is 'shallow' meaning that if a list is an element of the given list it will return that list.

± aList = ['a', 'b', 'c']

random.choice(aList)

>>> 'c'

random.choice([[1,2], [3,4], [5,6]])

>>> [5, 6]

Python Library Reference - random

± (define (choice aList)

(list-ref aList (random (length aList))))

(define aList '(a b c))

(choice aList)

>>> b

(choice '((1 2) (3 4) (5 6)))

>>> (3 4)

± l = ['a', 'b', 'c']

l[Math.floor(Math.random()*l.length)]

>>> 'b'

± #include <stdio.h>

#include <stdlib.h>



int main() {

int a[5] = {10, 20, 30, 40, 50};

int random_val;

random_val = rand() % sizeof(a);

printf("%d

", a[random_val]);

}

>>> 40

±

Random List Choice (Deep) Choose a random element of a list. If a list is chosen recursively run the function until the chosen element is not a list. ± Choose a random element of a list. If a list is chosen recursively run the function until the chosen element is not a list.

± This implementation may hit recursion limits on deeply nested lists. import random

def deepchoice(aList):

c = random.choice(aList)

if type(c) != type([]):

return c

else:

deepchoice(c)

deepchoice([[1,2], [3,4], [5, 6]])

>>> 5

± (define (choice aList)

(list-ref aList (random (length aList))))

(define (deepchoice aList)

(let ((c (choice aList)))

(if (not (list? c))

c

;else

(deepchoice c))))

(deepchoice '((1 2) (3 4) (5 6)))

>>> 4

± Add Entry for Javascript... Add Entry for C...

Task English Python Chicken Javascript C

Concepts, Design and Implementation

±

Keywords, Scope and Namespaces

±

Task English Python Chicken Javascript C

Keywords

± Does the language have any reserved keywords.

± import keyword

keyword.kwlist

['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield'] Guide to Python Introspection

± Scheme doesn't really have the concept of reserved keywords. However redefining core functions is usually a bad idea. ± abstract, boolean, break, byte, case, catch, char, class, const, continue, debugger, default, delete, do, double, else, enum, export, extends, false, final, finally, float, for, function, goto, if, implements, import, in, instanceof, int, interface, long, native, new, null, package, private, protected, public, return, short, static, super, switch, synchronized, this, throw, throws, transient, true, try, typeof, var, void, volatile, while, with ± auto, break, case, chart, const, continue, default, do, double, else, enum, extern, float, for, goto, if, int, long, register, return, short, signed, sizeof, static, struct, switch, typedef, union, unsigned, void, volatile, while ±

Can Redefine Keywords?

± Is it possible to redefine keywords? Remember this is almost always a bad idea.

± No ± Yes, but usually not a good idea. ± No ± No ±

Single or Multiple Namespace Multiple namespaces allow a function and variable to share the same name. The language determines the correct usage depending on the context of the code. ± Multiple namespaces allow a function and variable to share the same name. The language determines the correct usage depending on the context of the code.

± Single ± Single ± Single ± Single ±

Type System

±

Task English Python Chicken Javascript C

Strong or Weak Typing Strong: Objects may not be 'cast' onto an object with another type, "a"+1 returns error Weak: The language may silently coerce a type into another type so, "a"+1 could work. ± Strong: Objects may not be 'cast' onto an object with another type, "a"+1 returns error Weak: The language may silently coerce a type into another type so, "a"+1 could work.

± Strong ± Strong Scheme for C Programmers

± Weak ± Add Entry for C...

Static or Dynamic Typing Static: Types of variables are declared by the programmer. Dynamic: The language decides the type of the variables. ± Static: Types of variables are declared by the programmer. Dynamic: The language decides the type of the variables.

± Dynamic. ± Dynamic. ± Dynamic ± Static. ±

Task English Python Chicken Javascript C

Recursion Limit

± Is there a limit to the number of recursive calls.

± import sys

sys.getrecursionlimit()

>>> 1000

sys.setrecursionlimit(2000)

sys.getrecursionlimit()

>>> 2000

± If written with proper tail-recursion there is no recursion limit as the code is guaranteed to run in constant space. ± Usually around 1000, sometimes as low as 100 ± When you run out of stack space. This limit varies widely from platform to platform. ±

Properly Tail Recursive?

± Is the language properly tail recursive? A language is properly tail recursive if it correctly transforms tail calls into iteration.

± Not in Standard Python available in Stackless (and pypy?) ± Yes ± No ± No

Tail Recursion is supported in some compilers, such as GCC ±

Encouraged?

± Is using recursion encouraged by the language or community?

± Not usually ± Yes, recursion is the main looping method. ± Not usually ± Not usually ±

Task English Python Chicken Javascript C

Pure? Does the language prohibit side-effects? ± Does the language prohibit side effects?

± No ± No ± No ± No ±

Pure Subset? Does the language have a substantial subset that offers pure functional programming? ± Does the language have a substantial subset that offers pure functional programming?

± No ± Yes ± No ± No ±

Referential Transparency? Wikipedia - Referential Transparency ± Can code be written in the language that is referentially transparent? Is it in keeping with the style of the language to write code that is referentially transparent?

± Yes, but standard coding style is not referentially transparent. ± Yes, if code is written with it in mind. ± Yes, but standard coding style is not referentially transparent. ± Yes, but standard coding style is not referentially transparent. ±

Eager Evaluation

± Is the language capable of eager evaluation?

± Eager evaluation is the default model. ± Eager evaluation is the default model. Functional Programming in Scheme

± Eager evaluation is the default model. ± Eager evaluation is the default model. ±

Memory Management

±

Task English Python Chicken Javascript C

Type of Memory Management

± The type of memory management used. Some options are manual, garbage collected, reference counting.

± Reference Counting ± Garbage Collected ± Garbage Collected stackoverflow

± Manual ±

Objects have Unlimited Extent Objects will remain in memory until it can be proven they will no longer be needed. ± Will remain in memory until it can be proven they will no longer be needed.

± Yes ± Yes ± Yes ± Yes ±

Run Garbage Collector

± How to run the garbage collector if applicable.

± Python does not have a garbage collector, it uses reference counting.

± Python does have garbage collection that supplements the reference counting.

The gc module gives access to the GC.

For other implementations like Jython and IronPython the JVM/CLR GC is used and no reference counting takes place.

± Returns the number of free bytes.

#t runs a Major Collection (Default behavior)

#f runs a Minor Collection. (gc)

>>> 149308

(gc #t)

>>> 149308

(gc #f)

>>> 148680

Chicken Wiki - Unit library

± Javascript does not have a standard way to run the GC. ± C does not have a garbage collector. ±

Code Formatting

±

Task English Python Chicken Javascript C

Indentation Significant?

± Is indentation significant?

± Yes ± No (Yes with SRFI-49) SRFI-49

± No ± No ±

Where is Whitespace Significant?

± Where is whitespace significant?

± Indentation is used to group code.

Whitespace is used to separate keywords (def, if, etc...).

Aside from indentation, whitespace is not significant. ± Whitespace is used to separate elements of a list.

Additional whitespace is insignificant. ± Whitespace is used to separate elements of a list.

Additional whitespace is insignificant. ± Whitespace is used to separate identifiers.

All other use of whitespace is insignificant. ±

Source Code Character Set

± What character set is the source code written in.

± ASCII ± ASCII ± Unicode stackoverflow

± ASCII ±

Compiler, Interperter and IDE Notes

±