2
votes

So I'm writing a simple method that sums up the first 3 or less ints in a list but i'm confused about the match patterns.
I currently have

let sums l = match l with
    | [] -> 0
    | (h1::h2::h3::_) -> h1+h2+h3
    | [h1;h2;h3] -> h1+h2+h3
    | [h1;h2] -> h1+h2
    | [h1] -> h1

Does this cover all the cases? also how come for 3 or more elements I cant write something like [h1;h2;h3;_]?
Sorry if these question seem too simple, I just started learning OCaml and I cant find anything like this online.

1
Ocaml will give you a very explicit warning if it thinks the patterns do not cover all cases. - Str.

1 Answers

2
votes

Does this cover all the cases?

Yes, they cover all the cases, but I would write:

let sums l = match l with
  | [] -> 0
  | [h1] -> h1      
  | [h1; h2] -> h1+h2
  | h1 :: h2 :: h3 :: _ -> h1+h2+h3

Your [h1; h2; h3] is redundant since h1 :: h2 :: h3 :: _ matches it (with wildcard being [])

also how come for 3 or more elements I cant write something like [h1;h2;h3;_]?

well, you just can't. This syntax is not valid.
Edit: sorry I went crazy. This syntax is valid but it matches a list of four elements without binding the last element, which is not something you want.