ocaml

How should I check whether a number is in a list in OCaml?


Why is my code wrong?

# let ls = [1;2];;
val ls : int list = [1; 2]
# let inList a l = List.exists a l;;
val inList : ('a -> bool) -> 'a list -> bool = <fun>
# inList 1 ls;;
Error: This expression has type int but an expression was expected of type
         'a -> bool

Solution

  • Well, as you can see :

    # let inList a l = List.exists a l;;
    

    val inList : ('a -> bool) -> 'a list -> bool

    So a is of type 'a -> bool which means that a is a predicate on each element of the list.

    What you wanted to write was

    let inList a l = List.mem a l

    val inList : 'a -> 'a list -> bool

    TL;DR RTFM ;-) http://caml.inria.fr/pub/docs/manual-ocaml/libref/List.html