0
votes

Use recursion and list pattern matching to define a function exists with the following type: exists : (’a -> bool) -> ’a list -> bool The function should have the following behavior: for any predicate (function with boolean range) p and list l, a well-typed invocation (exists p l) should evaluate to true iff there exists some element x of l for which p x evaluates to true.

I am new to OCaml and do not know where to begin, any help would be great.

1
I like to be helpful, but I have to believe you're taking a class that provides some sort of material that will help you learn enough OCaml to do the assignment. This will be much more effective than starting from zero information here on SO. Provide some code that you wrote yourself and explain why it doesn't seem to be working. - Jeffrey Scofield
There is a such function in the module List of OCaml. Maybe if you're using it on some dummy examples, you may have an idea to how solve your problem. - alifirat

1 Answers

0
votes
#let rec exists p = function
    []            -> false
  | x::_ when p x -> true
  | _::tl         -> exists p tl;;

val exists : ('a -> bool) -> 'a list -> bool = <fun>

test :

# exists ((=)2) [4;3;2;1];;
- : bool = true
# exists ((=)2) [1;4];;
- : bool = false

About pattern matching :

let is_one = function
   1 -> true
 | x -> false

or

let is_one = function
   1 -> true
 | _ -> false    (* _ in any case *)

or

let is_one = function
   x when x=1 -> true
 | _          -> false 

test

# is_one 1;;
- : bool = true