2010-12-22 38 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)。