Lambda functions in Scheme

Andy Balaam

Contents

God uses Lisp

God uses Lisp

The Name

Alonso Church

The Name (2)

Anonymous functions

> (lambda (x y) (+ x y))
#<procedure>
> (define s (lambda (x y) (+ x y)))

> (s 2 5)
7

Defining functions revisited





(define (sum x y) (+ x y))

(define sum (lambda (x y) (+ x y)))

Example: building pairs



(define (mcons a b)
    (lambda (cmd)
        (if (equal? cmd "car")
            a
            b)))

(define (mcar pair) (pair "car"))
(define (mcdr pair) (pair "cdr"))

Example: building pairs (2)

> (define foo (mcons 1 2))

> (mcar foo)
1
> (mcdr foo)
2

Example: numbers - bricks




(define n0 (lambda () null))

(define (minc x) (lambda () x))

(define (mdec x) (x))

Example: numbers - mortar

(define n1 (minc n0))
(define n2 (minc n1))
(define n3 (minc n2))
(define n4 (minc n3))
(define n5 (minc n4))

Example: numbers - mortar (2)

(define n0 (lambda () null))
(define (minc x) (lambda () x))
(define n1 (minc n0))
(define n2 (minc n1))


> (n0)
()
> (n1)
#<procedure:n0>
> (n2)
#<procedure>

Example: numbers - questions



(define (mzero? x) (null? (x)))

(define (mequal? x y)
    (cond
        ((mzero? x) (mzero? y))
        ((mzero? y) (mzero? x))
        (else (mequal? (mdec x) (mdec y)))))

Example: numbers - questions (2)

> (mequal? n1 n0)
#f
> (mequal? n1 n1)
#t
> (mequal? n4 n5)
#f
> (mequal? n4 n4)
#t

Example: numbers - magic





(define (m+ x y)
    (if (mzero? y)
        x
        (m+ (minc x) (mdec y))))

Example: numbers - magic (2)

> (mequal? (m+ n0 n2) n2)
#t
> (mequal? (m+ n0 n2) n3)
#f
> (mequal? (m+ n0 n2) (m+ n1 n2))
#f
> (mequal? (m+ n2 n3) n5)
#t
> (mequal? (m+ n5 n5) (m+ n4 (m+ n3 n3)))
#t

Discussion

Alonzo Church Photo: Princeton Weekly Bulletin
(http://www.princeton.edu/pr/pwb/03/0505/7a.shtml)

God uses Lisp photo: Ben Brockert CC-By-SA (twitter: @wikkit)



You may use this presentation under the Creative Commons Attribution-ShareAlike 2.0 license.