You are looking at historical revision 36866 of this page. It may differ significantly from its current revision.
CHICKEN for Python programmers
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"])
a = sum(["1", "2"], start="")
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() # Deprecated
with open("my-file.txt") as f: f.read()
CHICKEN
(import (chicken io)) (call-with-input-file "my-file.txt" (lambda (port) (read-string #f port)))
read-string is defined in the (chicken io) module. call-with-input-file calls its argument procedure with the opened file as an argument. The first argument to {{read-string is the limit, which tells it how many characters to read. We use #f to indicate we want to read everything (no limit).
Reading the contents of a file and returning a list of lines
Python
open("my-file.txt").readlines()
with open("my-file.txt") as f: f.readlines()
CHICKEN
(call-with-input-file "my-file.txt" (lambda (port) (read-lines port)))
read-lines is also defined in the (chicken io) module.
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:
- Michele Simionato's blog series "The Adventures of a Pythonista in Schemeland"
- Jack Trades' language comparison table ("Pointless Programming Reference")