Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/wpf/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
OCaml中列表上的相互递归语法错误_Ocaml - Fatal编程技术网

OCaml中列表上的相互递归语法错误

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 [] -

我使用的是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 
    [] -> 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

我想你是对的!我今晚到家后再查。非常感谢。这很有效,谢谢你!我在哪里可以读到关于使用函数而不是匹配语法的内容?我想你是对的!我今晚到家后再查。非常感谢。这很有效,谢谢你!在哪里可以阅读有关使用函数而不是匹配语法的内容?