我在学校学习OCaml,最近遇到了一个我无法理解的作业计划,并希望有人可以向我解释。这是代码:
(* Natural numbers can be defined as follows:
type = ZERO | SUCC of nat;;
For instance, two = SUCC (SUCC ZERO) and three = SUCC (SUCC (SUCC ZERO)).
Write a function 'natadd' that adds two natural numbers in this fashion. *)
# type = ZERO | SUCC of nat;;
# let two = SUCC (SUCC ZERO);;
# let three = SUCC (SUCC (SUCC ZERO));;
# let rec natadd : nat -> nat -> nat =
fun n1 n2 ->
match n1 with
| ZERO -> n2
| SUCC n1 -> SUCC (natadd n1 n2)
;;
这是代码的示例输出:
# natadd two three;;
- : nat = SUCC (SUCC (SUCC (SUCC (SUCC ZERO))))
我不明白的是匹配声明。这是否意味着如果n1非零,那么它会添加SUCC并使用[SUCC n1]作为新参数代替n1进行递归调用?
答案 0 :(得分:3)
不,它不使用SUCC n1
作为递归调用的参数,它仅使用n1
(匹配的SUCC
的一部分)作为参数。然后将SUCC
应用于递归调用的结果。
代码可能有点令人困惑,因为有两个名为n1
的变量。更好的可能是
let rec natadd : nat -> nat -> nat = fun a b ->
match a with
| ZERO -> b
| SUCC a_pred -> SUCC (natadd a_pred b)