find - 如何访问 OCaml 中的列表

标签 find ocaml

我想写一个函数来检查列表中的每个项目是truefalse .如果至少一个元素是 false ,它将返回 true , 以便:

assert_eq "checkFalse [true; false; true]" (checkFalse [true; true; true]) false;
assert_eq "checkFalse [false; false]" (checkFalse [false; true]) true;

我是 OCaml 的绝对初学者,我不知道如何解决这个问题。我尝试使用 for 循环,例如:
let rec checkFalse (bools: bool list) : bool =
for i = 0 to bools.length do
    if bools.length == false then false
    else... (I don't know how to continue)

然后它说“未绑定(bind)记录字段......”

我也尝试使用 find ,例如:if (find false bools != Not_found) then true else false
但我的方法没有奏效。我来自 Java 背景。

最佳答案

看看List模块:http://caml.inria.fr/pub/docs/manual-ocaml/libref/List.html特别是 exists方法。对于你想要的,你可以简单地这样做:

List.exists (fun x -> not x) [true;true;...;false;...]
exists如果列表中的任何元素满足谓词(函数),函数将返回 true。在这种情况下,谓词是 fun x -> not x如果 x 将返回 true是假的。

对于一般列表访问,您通常使用模式匹配和递归,或使用函数 iter 来执行此操作。 , map , fold_left , 和 fold_right (除其他外)。这是 exists 的实现使用模式匹配:
let rec exists f l = match l with
  | [] -> false (* the list is empty, return false *)
  | h::t -> if (f h) then true (* the list has a head and a (possibly empty) tail.  Check the return value of the predicate 'f' when applied to the head *)
    else exists f t (* the predicate is false, recursively call the `exists` function on the tail *)

编辑:正如 Chuck 所发布的,而不是 fun x -> not x你可以简单地使用not .

另一种可能性是使用 mem功能:
List.mem false bools

关于find - 如何访问 OCaml 中的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4513910/

相关文章:

javascript - jQuery 查找文本并使用每个函数写入另一个标签属性

bash - 为什么我不能将查找结果通过管道传输到 cp,但它可以使用 exec?

ocaml - 可变记录字段和 { x with ... }

exception - 在 OCaml 中打破循环

ocaml - 如何在 OCaml 中同时匹配一个模式和它的一部分?

java - 找到并单击按钮 Java Robot

file - Ant:在目录中查找文件的路径

algorithm - 这个实现是尾递归的吗

types - 如何在 OCaml 中跨模块使用 GADT 而不会发出警告?