我想知道如何在 Ocaml 中构建一个函数,该函数使用 List.fold_left
找出列表中是否存在元素。
例子:
exists 3 [1;2;3;4;5]
=> true
这个函数的类型是:
a -> bool -> 'a list -> bool
我的想法是如何做到这一点的:
let exists k l = List.fold_left( fun a x-> a=x) k l
但显然是错误的。有什么建议怎么做吗?
最佳答案
let exists k l =
List.fold_left (fun b x -> b || x = k) false l
对@tonio 回答的两条评论:
||
而不是多余的 if ... then true else ...
。 =
) 而不是引用相等 ( ==
) 来比较值。 此外,
exists
在 List module 中可用。内置函数效率更高,因为它不必每次都遍历整个列表。
关于list - 使用 fold_left 在 OCaml 中搜索元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10413930/