# [基础软件理论与实践] 第二节作业实现 yhgu2000

yhgu2000 2022-11-14 20:42:48

#### 作业信息

1. Implement the substitution function N[v/x] : subst (N: lambda, x: string, v: value) : lambda
2. Think about how substitution works on arbitrary terms, i.e. N[M/x] where M could contain free variables.
3. Implement Church numberals and arithmetic functions using lambda calculus

#### 作业实现

##### 任务1、任务2

``````// Homework: implement the substitution
let rec subst = (x:string, v, a:lambda) => {
switch a {
| Var(y) => if x==y {v} else {a}
| Fn(y, body) => if x==y {a} else { Fn(y, subst(x, v, body)) }
| App(f, arg) => App(subst(x, v, f), subst(x, v, arg))
}
}
``````

``````// \x.x
let test_1 = Fn("x", Var("x"))
Js.Console.log(print_lambda(eval1(test_1)))

// \x.x \x.x = \x.x
let test_2 = App(Fn("x", Var("x")), Fn("x", Var("x")))
Js.Console.log(print_lambda(eval1(test_2)))

// \y.(\x.x y) \y.(\x.x y) = \x.(x \y.(\x.x y))
let test_3 = App(
Fn("y", Fn("x", App(Var("x"), Var("y")))),
Fn("y", Fn("x", App(Var("x"), Var("y"))))
)
Js.Console.log(print_lambda(eval1(test_3)))
``````

``````fun x -> x
fun x -> x
fun x -> x (fun y -> fun x -> x y)
``````
##### 任务3

``````// Homework: implement the arithmetic functions for peano numbers
let rec peano_add = (n: nat, m: nat): nat => {
switch n {
| Z => m
}
}
let rec peano_mul = (n: nat, m: nat): nat => {
switch n {
| Z => Z
| S(n') => peano_add(peano_mul(n', m), m)
}
}

// Homework: implement the arithmetic functions for church numbers
let church_add = (n: cnum<_>, m: cnum<_>): cnum<_> => {
(s, z) => n(s, m(s, z))
}
let church_mul = (n: cnum<_>, m: cnum<_>): cnum<_> => {
(s, z) => n((z) => m(s, z), z)
}
``````

``````// 1 + 2 = 3
Js.Console.log(peano_decode(peano_three))

// 2 * 3 = 6
let peano_six = peano_mul(peano_two, peano_three)
Js.Console.log(peano_decode(peano_six))

// 1 + 2 = 3
Js.Console.log(church_decode(church_three))

// 2 * 3 = 6
let church_six = church_mul(church_two, church_three)
Js.Console.log(church_decode(church_six))
``````

``````3
6
3
6
``````
##### 作业完成

...全文
208 1 打赏 收藏 转发到动态 举报

1 条回复

• 打赏
• 举报

231

rescript开发语言 个人社区 广东省·深圳市

• 近7日
• 近30日
• 至今