如何访问OCaml中的列表

Mar*_*ska 4 ocaml find

我想写一个函数,可以检查列表中的每个项是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循环,例如:

assert_eq "checkFalse [true; false; true]" (checkFalse [true; true; true]) false;
assert_eq "checkFalse [false; false]" (checkFalse [false; true]) true;
Run Code Online (Sandbox Code Playgroud)

然后它说"未绑定的记录字段......"

我也尝试过使用find: true

但我的方式不起作用.我来自Java背景.

非常感谢你!

Nik*_*chi 8

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

List.exists (fun x -> not x) [true;true;...;false;...]
Run Code Online (Sandbox Code Playgroud)

exists如果列表中的任何元素满足谓词(函数),则该函数将返回true.在这种情况下,fun x -> not x如果x为false ,则谓词将返回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 *)
Run Code Online (Sandbox Code Playgroud)

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

另一种可能是使用该mem功能:

List.mem false bools
Run Code Online (Sandbox Code Playgroud)


Joh*_*ski 7

let rec checkFalse xs =
    match xs with [] -> false
    | false :: _ -> true
    | _ :: tl -> checkFalse tl;;
Run Code Online (Sandbox Code Playgroud)


Chu*_*uck 6

最简单的方法就是let checkFalse = List.exists not.

List.exists将函数和列表作为参数,并告诉您传递的函数是否对列表中的任何元素返回true.not返回bool的否定.