Lambda functions in Scheme

Andy Balaam


God uses Lisp

God uses Lisp

The Name

Alonso Church

The Name (2)

Anonymous functions

> (lambda (x y) (+ x y))
> (define s (lambda (x y) (+ x y)))

> (s 2 5)

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")

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

Example: building pairs (2)

> (define foo (mcons 1 2))

> (mcar foo)
> (mcdr foo)

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)
> (n2)

Example: numbers - questions

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

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

Example: numbers - questions (2)

> (mequal? n1 n0)
> (mequal? n1 n1)
> (mequal? n4 n5)
> (mequal? n4 n4)

Example: numbers - magic

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

Example: numbers - magic (2)

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


Alonzo Church Photo: Princeton Weekly Bulletin

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.