Professional Documents
Culture Documents
Lambda
Lambda
Lambda
foo ( a, b, c )
Loops
while (a < b)
Use recursion
Side effects
Lambda Calculus
a := 1
CMSC 330
Turing Completeness
One solution
Lambda calculus
CMSC 330
CMSC 330
Lambda Expressions
Proposed in 1930s by
Alonzo Church
Stephen Cole Kleene
e ::= x
| x.e
| ee
Formal system
Designed to investigate functions & recursion
For exploration of foundations of mathematics
Now used as
variable
function
function application
CMSC 330
Three Conveniences
Scope of
To evaluate ( x.e1) e2
Evaluate e1 with x bound to e2
x y z is (x y) z
Same rule as OCaml
CMSC 330
CMSC 330
( x.( z.(x z))) y
( x.( z.(x z))) y
// since
z.(y z)
// final result
( x. z.x z) y
( x. y.x y) z
zy
fun z -> (y z)
CMSC 330
( y.(
10
( x.x ( x.x)) z
y.z y
( x. y.x y) ( z.zz) x
( x.x y) z
Parameters
Formal
Actual
( x.y) z
CMSC 330
( x.x) z
extends to right
e1[x/e2]
( x.x y) ( z.z)
( x.e1) e2
z.zz)y)x
(
z.zz)x
xx
11
CMSC 330
12
Beta-Reduction, Again
( x. y.x y) y ?
When we replace y inside, we dont want it to be
captured by the inner binding of y
y.y y
I.e., ( x. y.x y) y
Examples
Solution
Due to alpha conversion
So change ( x. y.x y) y to ( x. z.x z) y first
Now ( x. z.x z) y
z.y z
13
Encodings
z
y
y
14
true = x. y.x
false = x. y.y
if a then b else c
Examples
Booleans
Pairs
Natural numbers & arithmetic
Looping
expression: a b c
CMSC 330
15
Booleans (cont.)
CMSC 330
16
Pairs
Encoding of a pair a, b
false
Examples
CMSC 330
CMSC 330
Defined to be the
Examples
Booleans
not true
CMSC 330
( x. y.x y) y = ( x. z.x z) y
z.y z
// y
( x.x ( x.x)) z = ( y.y ( x.x)) z z ( x.x) // x
( x.x ( x.x)) z = ( x.x ( y.y)) z z ( y.y) // x
( x.e1) e2 e1[x/e2]
We must first alpha-convert variables as necessary
Usually performed implicitly (w/o showing conversion)
17
CMSC 330
18
Successor
succ 0 =
19
iszero 0 =
expressions)
22
Looping
Multiplication
1 = f. y.f y
2 = f. y.f (f y)
M * N = x.(M (N x))
Prove 1+1 = 2
Arithmetic (cont.)
20
In prefix notation (+ M N)
21
CMSC 330
CMSC 330
Addition
0 = f. y.y
Since ( x.y) z
M + N = x. y.(M x)((N x) y)
Example
0 = f. y.y
1 = f. y.f y
Example
IsZero?
succ = z. f. y.f (z f y)
0 = f. y.y
1 = f. y.f y
2 = f. y.f (f y)
3 = f. y.f (f (f y))
i.e., n = f. y.<apply f n times to y>
D D = ( x.x x) ( x.x x)
( x.x x) ( x.x x) = D D
So D D is an infinite loop
In general, self application is how we get looping
23
CMSC 330
24
Example
25
Discussion
CMSC 330
26
In practice
false 0
y.y
if 0 then ...
false = x. y.y
0 = x. y.y
27
CMSC 330
28
e ::= n | x | x:t.e | e e
t ::= int | t
29
CMSC 330
30
Summary
Lambda calculus shows issues with
Scoping
Higher-order functions
Types
CMSC 330
31