我想写一个函数来检查列表中的每个项目是true
或 false
.如果至少一个元素是 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/