Chicken for Python programmers

  1. Chicken for Python programmers
  2. Hello, world!
    1. Python
    2. Chicken
  3. Definitions, assignment and bindings
    1. Python
    2. Chicken
  4. Strings
    1. Concatenating
      1. Python
      2. Chicken
    2. Splitting a string
      1. Python
      2. Chicken
  5. File I/O
    1. Reading the contents of a file and returning a string
      1. Python
      2. Chicken
    2. Reading the contents of a file and returning a list of lines
      1. Python
      2. Chicken
  6. Conditionals
    1. Single condition
      1. Python
      2. Chicken
    2. Multiple conditions
      1. Python
      2. Chicken
  7. Iteration
    1. Iterating through and printing the elements of a list
      1. Python
      2. Chicken
    2. Applying a procedure/function to each item of a list
      1. Python
      2. Chicken
  8. Other references

Hello, world!

Python

print "Hello, world!"

Chicken

(print "Hello, world!")

Definitions, assignment and bindings

Python

Python has only one operator for both assignments and definitions of variables (=).

a = 0

Chicken

Defining a variable:

(define a 0)

Assigning a variable a value:

(set! a 0)

PS: Chicken automatically defines a global variable when a variable is set without being defined. However, it is best practice (and most compatible with other Schemes) to define all variables.

Binding a value to a variable:

(let ((a 0))
   a)

Strings

Concatenating

Python

a = "1" + "2"
a = "".join(["1", "2"])

Chicken

(string-append "1" "2")
(conc "1" "2")
(string-intersperse '("1" "2") "")

Splitting a string

Python

"this is a string".split()

Chicken

(string-split "this is a string")

File I/O

Reading the contents of a file and returning a string

Python

open("my-file.txt").read()

Chicken

(read-all "my-file.txt")

read-all is defined in Unit utils.

Reading the contents of a file and returning a list of lines

Python

open("my-file.txt").readlines()

Chicken

(read-lines "my-file.txt")

read-lines is defined in Unit utils.

Conditionals

Single condition

Python

"yes" if 1<2 else "no"

Chicken

(if (< 1 2) "yes" "no")

PS: in Scheme, the result of the evaluation of an if form is passed to its continuation.

Multiple conditions

Python

result = None
if 1 < 2:
    result = "1 < 2"
elif 1 > 2:
    result = "1 > 2"
else:
    result = "1 = 2"

Chicken

(cond ((< 1 2) "1 < 2")
      ((> 1 2) "1 > 2")
      (else "1 = 2"))

PS: in Scheme, the result of the evaluation of a cond form is passed to its continuation.

Iteration

Iterating through and printing the elements of a list

Python

l = [1, 2, 3, 4]
for i in l:
    print i

Chicken

(define l '(1 2 3 4))
(for-each print l)

Applying a procedure/function to each item of a list

Python

l = [1, 2, 3, 4]

def add10(n):
    return n + 10

[ add10(i) for i in l ]

Chicken

(define l '(1 2 3 4))

(define (add10 n) (+ n 10))

(map add10 l)

Other references

Other interesting reads to check out: