Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using fold_left to search for an element in OCaml

Tags:

list

ocaml

I'm wondering how can I build a function in Ocaml that uses List.fold_left to find out if an element exists in a list. Example:

exists 3 [1;2;3;4;5] 
=> true

The type of this function is: a -> bool -> 'a list -> bool

My idea how to do it is as follows:

let exists k l = List.fold_left( fun a x-> a=x) k l

but obviously is wrong. Any suggestion how to do it?

like image 292
João Oliveira Avatar asked Dec 17 '22 00:12

João Oliveira


2 Answers

let exists k l =
    List.fold_left (fun b x -> b || x = k) false l

Two comments on @tonio's answer:

  • Use || instead of superfluous if ... then true else ....
  • Use structural equality (=) instead of reference equality (==) for comparing values.

Moreover, exists is available in List module. The built-in function is more efficient since it doesn't have to go through the whole list every time.

like image 93
pad Avatar answered Jan 08 '23 09:01

pad


You should use something like

let exists k l =
    List.fold_left(
      fun a x -> if x == k then true else a)
      false l
;;

You have an initial value of false, and pass it while iterating over the list. Once the searched element is found, set the value to true, and pass it along. If the element in the list is not what you search, pass the value you had as input: it is either the initial false, or true if the element you search for has already been found.

like image 32
tonio Avatar answered Jan 08 '23 07:01

tonio