【问题标题】:Syntax error with mutual recursion on a list in OCamlOCaml中列表上的相互递归的语法错误
【发布时间】:2018-05-17 22:47:21
【问题描述】:

我正在使用 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 在 ;; 上引发语法错误在代码的最后。我不确定从哪里开始弄清楚这个错误到底是什么。

【问题讨论】:

    标签: ocaml


    【解决方案1】:

    我怀疑您忘记添加 let 绑定的 in ... 部分 - 粗体

    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

    这将以+ 开始序列,即1 + 2 - 3 ...

    如果您希望它以- 开头...

    ...
    in
    sub list

    我们可以将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
    

    【讨论】:

    • 我认为你是对的!我今晚回家时检查一下。谢谢!
    • 成功了,谢谢!我在哪里可以阅读有关使用函数而不是匹配语法的信息?
    猜你喜欢
    • 2013-06-01
    • 2015-06-10
    • 1970-01-01
    • 2014-03-15
    • 1970-01-01
    • 1970-01-01
    • 2019-10-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多