Encoding natural numbers datatype nat = Z | S of nat val zero = Z - - PowerPoint PPT Presentation

encoding natural numbers
SMART_READER_LITE
LIVE PREVIEW

Encoding natural numbers datatype nat = Z | S of nat val zero = Z - - PowerPoint PPT Presentation

Encoding natural numbers datatype nat = Z | S of nat val zero = Z val one = S Z val two = S (S Z) val three = S (S (S Z)) Define fold s.t. fold f x replaces S 7! f and Z 7! x fun fold f x Z = x | fold f x (S n) = f (fold f x n) Example:


slide-1
SLIDE 1

Encoding natural numbers

datatype nat = Z | S of nat val zero = Z val one = S Z val two = S (S Z) val three = S (S (S Z)) Define fold s.t. fold f x replaces S

7! f and Z 7! x

fun fold f x Z = x | fold f x (S n) = f (fold f x n) Example: fold (fn k => k+1) zero three

+ 3

Church: represent n as

f :x :fold f x n.
slide-2
SLIDE 2

Church Numerals

Encoding natural numbers as lambda-terms zero

= f :x :x
  • ne
= f :x :f x

two

= f :x :f (f x )

n

= f :x :f (n)x

succ

= n :f :x :f (n f x )

plus

= n :m :n succ m

times

= n :m :n (plus m ) zero
slide-3
SLIDE 3

Church Numerals in

  • zero

= \f.\x.x; succ = \n.\f.\x.f (n f x); plus = \n.\m.n succ m; times = \n.\m.n (plus m) zero; ...

  • > four;

\f.\x.f (f (f (f x)))

  • > three;

\f.\x.f (f (f x))

  • > times four three;

\f.\x.f (f (f (f (f (f (f (f (f (f (f (f x)))))))))))

slide-4
SLIDE 4

Reduction rules

Central rule based on substitution

(x :M )N
  • ! M
[x 7! N ℄

(BETA) Structural rules: Beta-reduce anywhere, any time N

  • ! N′

MN

  • ! MN′

M

  • ! M′

MN

  • ! M′N

M

  • ! M′
x :M
  • !
x :M′
slide-5
SLIDE 5

Free variables

x is free in x x is free in M

_ x is free in N

x is free in MN x is free in M x

6= x′

x is free in

x′ :M
slide-6
SLIDE 6

Exercise: Free Variables

What are the free variables in: \x.\y. y z \x.x (\y.x) \x.\y.\x.x y \x.\y.x (\z.y w) y (\x.z) (\x.\y.x y) y

slide-7
SLIDE 7

Exercise: Free Variables

What are the free variables in: \x.\y. y z

  • z

\x.x (\y.x)

  • nothing

\x.\y.\x.x y

  • nothing

\x.\y.x (\z.y w)

  • w

y (\x.z)

  • y z

(\x.\y.x y) y

  • y
slide-8
SLIDE 8

Capture-avoiding substitution

x [x

7! M ℄ =

M y

[x 7! M ℄ =

y

(YZ )[x 7! M ℄ = (Y [x 7! M ℄)(Z [x 7! M ℄) (x :Y )[x 7! M ℄ = x :Y (y :Z )[x 7! M ℄ = y :Z [x 7! M ℄

if x not free in Z or y not free in M

(y :Z )[x 7! M ℄ = w :(Z [y 7! w ℄)[x 7! M ℄

where w not free in Z or M Last transformation is renaming of bound variables

slide-9
SLIDE 9

Renaming of bound variables

So important it has its own Greek letter: w not free in Z

y :Z
  • !
w :(Z [y 7! w ℄)

(ALPHA) Also has structural rules