Chap4 Lambda Calculus
Chap4 Lambda Calculus
CO2039
02 REDUCTION
04 CONCLUSION
2
Brief History
3
Church-Turing Test
4
CALCULATING WITH
01 LAMBDA CALCULUS
5
What is Functional Language?
6
No-Side-Effects Language Test
Within the scope of specific declarations of x1, x2, …, xn, all occurrences of
an expression e containing only variables x1, x2, …, xn, must have the same
value.
begin
integer x=3; integer y=4;
5*(x+y)-3
… // no new declaration of x or y //
4*(x+y)+1
end
7
Expressions and Functions
● Expressions
x + y x + 2*y + z
● Functions
λx.(x+y) λz.(x+2*y+z)
● Application
(λx.(x+y)) 3 = 3 + y
(λz.(x+2*y+z)) 5 = x + 2*y + 5
● Parsing: λx.f (f x) = λx.(f (f(x)))
8
Terminology
● λx.t
● λx.x y
y is free in the term
λx.x y
x is bound in the term
λx.x y
9
Free & Bound Variables (1)
10
Free & Bound Variables (2)
11
02 REDUCTION
12
CBV Operational Semantics
13
Examples
14
Higher-order Functions
15
Declaration of “Syntactic Sugar”
def f(x):
return x + 2
print(f(5)) # Output: 7
(λf.f(5))(λx.x+2)
16
Rules
● α-reduction (renaming)
○ λy.M ⇒α λv.(M [y v])
where v does not occur in M.
● β-reduction (substitution)
○ (λx.M) N ⇒β M [x N]
17
Attention
18
Attention (cont.)
19
IMPLEMENTING BUILT-IN
03 CONSTANTS &
FUNCTIONS
20
Building in Constants and Functions (1)
We can represent things, like for example, numbers and booleans using λ-abstractions.
Example:
● We can encode booleans, consider representing “true” and “false” as functions
named “tru” and “fls”
● How do we define these functions? Think about how “true” and “false” can be used.
● They can be used by a testing function:
○ “test b then else” returns “then” if b is true and returns “else” if b is false.
○ The only thing the implementation of test will do with b is to apply it.
○ The functions “tru” and “fls” must distinguish themselves when they are
applied.
21
Building in Constants and Functions (2)
The encoding:
tru = λt.λf.t
fls = λt.λf.f
test = λx.λthen.λelse.x then else
Example:
test tru (λx.t1) (λx.t2)
→* (λt.λf.t) (λx.t1) (λx.t2)
→* λx.t1
22
Building in Constants and Functions (3)
23
Numbers
0 := λf.λx.x
1 := λf.λx.f x
2 := λf.λx.f (f x)
3 := λf.λx.f (f (f x))
4 := λf.λx.f (f (f (f x)))
SUM := λm.λn.λf.λx.m f (n f x)
PROD := λm.λn.λf.λx.m (n f) x
SUBTRACT := λm.λn.n PRED m
⇒ Apply the predecessor function (PRED) n times to m
⇒ How to compute predecessor? Can implement using pairs!
24
Data Structures - Pair
25
Data Structures - List
Can turn our method of pairing arbitrary normal form expressions into building up lists.
All we need is a way to mark the end of the list (NIL) and a way to tell if we’re at the end
of the list (ISEMPTY).
NIL := λx.TRUE ISEMPTY := λp.p (λx.λy.FALSE)
ISEMPTY NIL = (λp.p (λx.λy.FALSE)) (λx.TRUE)
➞ (λx.TRUE) (λx.λy.FALSE) ➞ TRUE
ISEMPTY (PAIR E F) = (λp.p (λx.λy.FALSE)) (λf.f E F)
➞ (λf.f E F) (λx.λy.FALSE) ➞ (λx.λy.FALSE) E F ➞ FALSE
26
Predecessor
27
04 CONCLUSION
28
Conclusion
29
Thank you for your
attention!
https://www.cse.hcmut.edu.vn