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?
let exists k l =
List.fold_left (fun b x -> b || x = k) false l
Two comments on @tonio's answer:
|| instead of superfluous if ... then true else ....=) 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With