我正在使用OCaml v 4.00.1。我试图使用相互递归编写一个函数来获取一个列表并返回一个int。 int是获取列表的交替元素并相互相加和相减的结果。例如,列表[1; 2; 3; 4]将导致1 + 2 - 3 + 4 = 4.
我的代码如下:
let alt list =
let rec add xs = match xs with
[] -> 0
| x::xs -> x + (sub xs)
and sub xs = match xs with
[] -> 0
| x::xs -> x - (add xs);;
OCaml在;;上抛出语法错误在代码的最后。我不确定从哪里开始弄清楚这个错误究竟是什么。
答案 0 :(得分:4)
我怀疑您忘记添加let alt list =
let rec add xs =
match xs with
| [] -> 0
| x::xs -> x + (sub xs)
and sub xs =
match xs with
| [] -> 0
| x::xs -> x - (add xs)
in
add list
绑定的+
部分 - 粗体
-
这将以...
in
sub list
开始序列,即1 + 2 - 3 ...
如果您希望它以match
...
function
我们可以为let alt list =
let rec add = function
| [] -> 0
| x::xs -> x + (sub xs)
and sub = function
| [] -> 0
| x::xs -> x - (add xs)
in
add list
交换printAccountSummary: function()
{return "Welcome!" + "\n" + "Your balance is currently $1000 and your interest rate is 1%."}
};
console.log(savingsAccount.printAccountSummary()); // method
语法,并在此处改进了可读性
Welcome!
Your balance is currently $1000 and your interest rate is 1%.