4

So what I have this list of ints, let's say it is

let a = [14, 22, 47] in

And what I want to do is check if some other identifier is equal to ANY of the elements in the list. I could obviously do:

if (x = 14 || x = 22 || x = 47) then do something

but this seems cumbersome for bigger lists. Is there an easier way in OCaml? I know Python has the "in" operator.

sebster
  • 79
  • 2
  • 2
  • 8

3 Answers3

12
$ ocaml
        OCaml version 4.01.0

# List.mem;;
- : 'a -> 'a list -> bool = <fun>
# List.mem 3 [1;2;3];;
- : bool = true
# List.mem 8 [1;2;3];;
- : bool = false

(I'd suggest reading through the list of functions in the List module. You want to be familiar with all of them.)

Jeffrey Scofield
  • 65,646
  • 2
  • 72
  • 108
3

List.mem is what you are looking for.

Jackson Tale
  • 25,428
  • 34
  • 149
  • 271
3

You can also create a function as follows:

let rec contains element = function
  | a::c -> if (a = element) then true else (contains element c)   
  | []   -> false
Flux
  • 9,805
  • 5
  • 46
  • 92