Instructor: Stefan Mitsch
; This (recursive) function calculates the length of a linked list.
(define (length l)
(if (equal? l ())
0
(+ 1 (length (cdr l)))))
5
"hello world"
'helloworld
; (1 + 2) * 3 would be written in Scheme as follows
(* (+ 1 2) 3)
(+ 10 5 2)
(- 10 5 2)
+ 1 2
1 + 2
1 2 +
square with parameter n
(define (square n) (* n n))
square function
(square 5)
square function twice
(square (square 5))
(define (f param_1 param_2 ... param_m)
e_1 e_2 ... e_n)
m arguments
e_1, e_2, ..., e_n-1 evaluated for side effect
e_n is evaluated and its result is returned
return keyword, no statements, just expressions
begin like C comma operator, but not needed
(define (f param_1 param_2 ... param_m)
(begin e_1 e_2 ... e_n))
f with m arguments
(f e_1 e_2 ... e_m-1)
(square 5)
square 5
(f M N) is
evaluated by
M to value U
N to value V
f with values U and V
define is a special form, not a function, so it does not obey this convention
= operator tests number equality
(define (zero n) (= n 0))
#t and #f
if is a non-strict special form
(define (safe-divide m n)
(if (= n 0)
"divide by zero"
(/ m n)))
(define (fact n)
(if (<= n 1)
1
(* n (fact (- n 1)))))
int fact (int n) {
return (n <= 1) ? 1 : n * fact (n - 1);
}
(cons 1 2)
(cons "hello" "world")
(cons 1 "world")
car and cdr functions extract components
(car (cons 1 "world"))
(cdr (cons 1 "world"))
car position for elements
cdr position for next cons cell
() and cons
()
(cons 41 ())
(cons 11 (cons 21 (cons 31 (cons 41 ()))))
quote special form prevents evaluation
(quote (3))
(quote (1 2 3))
' is shorthand for quote
'(3)
'(1 2 3)
list function evaluates args, puts results in a list
(list 3)
(list 1 2 3)
(list 1 2 (+ 1 2))
eq? for pointer equality
(eq? (cons 1 (cons 2 (cons 3 ()))) '(1 2 3))
equal? for structural equality
(equal? (cons 1 (cons 2 (cons 3 ()))) '(1 2 3))
(define (length l)
(if (equal? l ())
0
(+ 1 (length (cdr l)))))
(length '(5 6 7 8 9))
class Node {
int item;
Node next;
}
static int length (Node data) {
return (data == null) ? 0 : 1 + length (data.next)
}
(length '(5 6 7))
--> (if (equal? '(5 6 7) '()) 0 (+ 1 (length (cdr '(5 6 7)))))
--> (+ 1 (length (cdr '(5 6 7))))
--> (+ 1 (length '(6 7)))
--> (+ 1 (+ 1 (length '(7))))
--> (+ 1 (+ 1 (+ 1 (length '()))))
--> (+ 1 (+ 1 (+ 1 0)))
--> (+ 1 (+ 1 1))
--> (+ 1 2)
--> 3
(symbol? 'x)
(number? 1)
(boolean? #t)
(string? "x")
(procedure? (lambda (x) (+ x 1)))
(pair? '(1 . 2))
(pair? '(1))
; (pair? '())
; (list? '(1 . 2))
(list? '(1))
(list? '())
'().
eval for evaluation.
(quote exp) causes exp to
be parsed without evaluation, resulting in an S-Exp.
(+ 1 2)
'(+ 1 2)
(cons '+ '(1 2))
(car '(+ 1 2))
eval function evaluates an expression
(eval (cons '+ '(1 2)))
(define (add-all l) (eval (append '(+) l)))
(add-all '(1 2 3))
read function reads an expression
(read)
(eval (read))
(eval (append '(+) (read)))