231
社区成员
发帖
与我相关
我的任务
分享
本次作业基于课程信息给出的示例代码实现。
才知道示例代码里已经留处了写作业的 TODO,回想起自己第一次傻傻地从 PPT 里拷代码结果报了很多编译错误……
补充 src/Lambda.res
中 subst
函数:
// 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)
补充 src/Nat.res
中四个函数定义如下:
// Homework: implement the arithmetic functions for peano numbers
let rec peano_add = (n: nat, m: nat): nat => {
switch n {
| Z => m
| S(n') => peano_add(n', S(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
let peano_three = peano_add(peano_one, peano_two)
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
let church_three = church_add(church_one, church_two)
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
上周比较忙,这次迟交了,不好意思 😆