OCaml中列表上的相互递归语法错误
我使用的是OCAMLV4.00.1。我正在尝试使用相互递归编写一个函数,以获取一个列表并返回一个int。int是获取列表中的交替元素并将它们相互相加和相减的结果。例如,列表[1;2;3;4]将导致1+2-3+4=4 我的代码如下:OCaml中列表上的相互递归语法错误,ocaml,Ocaml,我使用的是OCAMLV4.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 [] -
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在;;上抛出语法错误;;在代码的最后。我不确定从何处开始找出这个错误的真正原因。我怀疑您忘了将
添加到let
binding–粗体中的部分
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
我们可以为函数
交换匹配
语法,在这里提高了可读性
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
我怀疑您忘了在let
binding中添加。
部分–更改粗体
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
我们可以为函数
交换匹配
语法,在这里提高了可读性
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
我想你是对的!我今晚到家后再查。非常感谢。这很有效,谢谢你!我在哪里可以读到关于使用函数而不是匹配语法的内容?我想你是对的!我今晚到家后再查。非常感谢。这很有效,谢谢你!在哪里可以阅读有关使用函数而不是匹配语法的内容?