Chapter 10: Functional Languages

Origins

Characteristics and Concepts

Other common characteristics and concepts

Scheme

gosh> ((lambda (x) (* x x)) 3)
9

Let it be

gosh> (let ( (a 3)
             (b 4)
             (square (lambda(x) (* x x)))
             (plus +))
        (sqrt (plus (square a) (square b))))
5
gosh> b
*** ERROR: unbound variable: b
Stack Trace:
_______________________________________

The car and cdr

gosh> (car '(1 2 3 4 5))
1
gosh> (cdr '(1 2 3 4 5))
(2 3 4 5)
gosh> (cons 1 '(2 3 4 5))
(1 2 3 4 5)

Other useful bits

gosh> (null? () )
#t
gosh> (null? '(2))
#f

Other useful bits

gosh> (memq 'a '(a b c d))
(a b c d)
gosh> (memq 'b '(a b c d))
(b c d)
gosh> (memq 'c '(a b c d))
(c d)

Other useful bits

gosh> (member '(a) '((a) b c d))
((a) b c d)
gosh> (member '(b) '((a) b c d))
#f
gosh> (member '(b) '((a) (b) c d))
((b) c d)

Conditionals

gosh> (if (< 2 3) 4 5)
4
gosh> (cond
        ((< 3 2) 1)
        ((< 4 3) 2)
        (else 3))
3

Assignment, sequencing, and iteration

gosh> (define iter-fib (lambda (n)
        (do ((i 0 (+ i 1))
             (a 0 b)
             (b 1 (+ a b)))
          ((= i n) b)
          (display b)
          (display " "))))
gosh> (iter-fib 10)
1 1 2 3 5 8 13 21 34 55 89

Programs as lists

gosh> (eval '(+ 3 4) (interaction-environment))
7
gosh> (eval (quote (+ 3 4)) (interaction-environment))
7

Programs as lists

gosh> (+ 3 4 5)
12
gosh> (apply + '(3 4 5))
12
gosh> (map + '(3 4 5))
(3 4 5)
gosh> (apply + '(3 4 5) '(8 9 10))
*** ERROR: operation + is not defined between (3 4 5) and 8
gosh> (map + '(3 4 5) '(8 9 10))
(11 13 15)

Using just eval and apply, you can write a Scheme interpreter in Scheme

Evaluation order

Evaluation order

Strictness and Laziness

Strictness and Laziness

Streams and monads

Monads

Higher-order functions

Prelude> let plus a b = a + b
Prelude> let x = plus 3
Prelude> x 7
10
Prelude> x 100
103
Prelude> let y = plus 21
Prelude> y 200
221
Prelude> y 300
321

Currying...

Prelude> foldl plus 0 [1..10]
55