I want to write a function that could check every item in a list is true or false. If at least one element is false, it will return true, so that:
assert_eq "checkFalse [true; false; true]" (checkFalse [true; true; true]) false;
assert_eq "checkFalse [false; false]" (checkFalse [false; true]) true;
I am an absolute beginner in OCaml and I don’t know how to approach this. I tried using a for loop, something like:
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)
Then it said “Unbound record field….”
I also tried using find like:
if (find false bools != Not_found) then true else false
But my ways did not work. I came from a Java background.
Take a look at the
Listmodule: http://caml.inria.fr/pub/docs/manual-ocaml/libref/List.html specifically theexistsmethod. For what you want, you can simply do this:The
existsfunction will return true if any element in the list satisfies the predicate (the function). In this case, the predicate isfun x -> not xwhich will return true ifxis false.For general list access, you generally do this using pattern matching and recursion, or using the functions
iter,map,fold_left, andfold_right(among others). Here’s an implementation ofexistsusing pattern matching:edit: as Chuck has posted, instead of
fun x -> not xyou can just simply usenot.Another possibility is to use the
memfunction: