[英]I started working in ocaml and i can't figure out a small thing about nat types
我正在尝试编写类型为 nat -> nat -> nat -> nat 的 function,我将其命名为 sudan_nat 它按照苏丹 function 的原则工作 **
Wikipedia:
https://en.wikipedia.org/wiki/Sudan_function
//This is the type definition
type nat = Zero | Succ of nat
let add_nat m n =
let rec helper m = match m with Zero -> n | Succ m -> Succ (helper m)
in helper m
let zero_nat = Zero
let one_nat = Succ zero_nat
let two_nat = Succ one_nat
let four_nat = add_nat two_nat two_nat`
let sudan_nat m n p =
let rec helper m n = match m with Zero -> n | Succ m -> Succ (helper m n)
in helper (add_nat (add_nat m n) p) one_nat
这是我为 sudan_nat 写的代码
我测试 output 的情况是 ((sudan_nat one_nat two_nat two_nat) = (add_nat (add_nat four_nat four_nat) four_nat))
Succ (Succ (Succ (Succ (Succ (Succ Zero)))))
这是左侧的结果
Succ
(Succ
(Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ (Succ Zero)))))))))))
这是右侧的结果我已经摸索了几个小时现在欢迎任何建议谢谢
four_nat
是Succ (Succ (Succ (Succ Zero)))
。 那是 4 个Succ
构造函数。 你把其中的 3 个加在一起,所以你有... 12。4 乘以 3 = 12。
当谈到评估sudan_nat nat_one nat_two nat_two
时,它分解了:
sudan_nat nat_one nat_two nat_two
helper (add_nat (add_nat nat_one nat_two) nat_two) one_nat
helper (add_nat (add_nat Zero nat_two) nat_two) one_nat
helper (add_nat nat_two nat_two) one_nat
helper nat_four one_nat
...
Succ (Succ (Succ (Succ (Succ Zero))))
作为额外的风格建议,您可能希望定义一个模块来组织您的代码。
module Nat =
struct
type t = Zero | Succ of t
let add m n =
let rec helper m =
match m with
| Zero -> n
| Succ m -> Succ (helper m)
in
helper m
let one = Succ Zero
let two = Succ (Succ Zero)
let four = add two two
let sudan m n p =
let rec helper m n =
match m with
| Zero -> n
| Succ m -> Succ (helper m n)
in
helper (add (add m n) p) one
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.