【问题标题】:Int list to int OCaml整数列表到整数 OCaml
【发布时间】:2013-01-16 08:25:10
【问题描述】:

我是 OCaml 的新手,所以我正在学习基础知识。我正在编写一个函数来确定列表是否包含给定的整数。

let rec int_member (x: int) (l: int list) : bool 
begin match l with
| [] -> false
| hd :: rest -> x = hd || int_member rest x
end

作为测试用例...

let test (): bool =
(int_member 1 [1;2;3]) = true
;; run_test "contains 1 [1;2;3]" test

我收到一条错误消息,提示“此表达式的类型为 int 列表,但表达式应为 int 类型”。我该如何解决这个问题?

【问题讨论】:

    标签: ocaml


    【解决方案1】:

    如果您查看您的递归调用,您应该会发现您没有完全正确地传递参数!否则这段代码是相当不错的。 (我看到缺少=,并且在这里使用beginend 不是很惯用的OCaml。你可以把它们排除在外。)

    【讨论】:

    • 另一个问题。关于风格,有没有另一种写这个表达的方式? if (a = k) then b else (assock rest)
    【解决方案2】:

    int_member 休息 x

    int_member 的第一个参数应该是 int。您将 int list 作为第一个参数传递。这就是错误消息所抱怨的内容。

    你只是改变了参数的顺序。

    PS:代码中的begin ... end 是多余的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-12-05
      • 1970-01-01
      • 2016-08-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多