Mariska
Mariska

Reputation: 1953

How to access a list in OCaml

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.

Upvotes: 5

Views: 11047

Answers (4)

Simon marc
Simon marc

Reputation: 1003

let checkFalse = List.exists (fun elem -> elem = false) your_list in

doc: val exists : ('a -> bool) -> 'a list -> bool

exists p [a1; ...; an] checks if at least one element of the list satisfies the predicate p.

That is, it returns (p a1) || (p a2) || ... || (p an).

Upvotes: 0

Niki Yoshiuchi
Niki Yoshiuchi

Reputation: 17551

Take a look at the List module: http://caml.inria.fr/pub/docs/manual-ocaml/libref/List.html specifically the exists method. For what you want, you can simply do this:

List.exists (fun x -> not x) [true;true;...;false;...]

The exists function will return true if any element in the list satisfies the predicate (the function). In this case, the predicate is fun x -> not x which will return true if x is false.

For general list access, you generally do this using pattern matching and recursion, or using the functions iter, map, fold_left, and fold_right (among others). Here's an implementation of exists using pattern matching:

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 *)

edit: as Chuck has posted, instead of fun x -> not x you can just simply use not.

Another possibility is to use the mem function:

List.mem false bools

Upvotes: 9

Chuck
Chuck

Reputation: 237010

The simplest way would just be let checkFalse = List.exists not.

List.exists takes a function and a list as arguments, and tells if the function you passed returns true for any element in the list. not returns the negation of a bool.

Upvotes: 6

Johan Kotlinski
Johan Kotlinski

Reputation: 25739

let rec checkFalse xs =
    match xs with [] -> false
    | false :: _ -> true
    | _ :: tl -> checkFalse tl;;

Upvotes: 7

Related Questions