I try to write a simple OCaml program that returns true if the a list contains all even integers and false if it does not.
let rec allEven l =
List.hd l mod 2 = 0 && allEven (List.tl l);;
It didn’t give me any error when I typed in the code. But whenever I enter a list that starts with an even number like allEven [2;3] it give me the error message “Failure “hd””. Not really sure why. Thanks!!
List.hd will raise Failure “hd” on the empty list. To correct your function, use pattern matching:
Also, the modulo operator in OCaml is “mod” not “%”