2010-12-22 39 views
4

我想编写一个函数来检查列表中的每个项目是true还是false。如果至少有一个元素为假,则返回true,以便:如何访问OCaml中的列表

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) 

然后它说:“未绑定记录字段......”

我用找到像也尝试: if (find false bools != Not_found) then true else false

但我的方式做不行。我来自Java背景。

非常感谢!

+0

您很少需要在OCaml中指定类型。`让rec checkFalse bools =`和你写的一样。 – 2010-12-22 21:55:35

回答

8

看一看的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。

对于一般列表访问,你一般做这个使用模式匹配和递归,或者使用功能itermapfold_leftfold_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 *) 

编辑:为查克已经发布,而不是fun x -> not x你可以简单地使用not

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

List.mem false bools 
7
let rec checkFalse xs = 
    match xs with [] -> false 
    | false :: _ -> true 
    | _ :: tl -> checkFalse tl;; 
6

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

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

0

让checkFalse = List.exists(乐趣ELEM - > ELEM = FALSE)在

DOC your_list: VAL存在:( 'A - >布尔) - >' 列表 - > BOOL

存在p [a1; ...; an]检查列表中的至少一个元素是否满足谓词p。

也就是说,它返回(p a1)|| (p a2)|| ... || (p an)。