Here is a snippet of code from my book, and I’m not sure about how the matching works apparently because it seems the first case matches everything. Here are the warnings Ocaml throws at me:
# let zero = 0;;
# let one = 1;;
# let rec fib i =
match i with
zero -> zero
| one -> one
| j -> fib (j - 2) + fib (j - 1);;
Characters 57-60:
Warning: this match case is unused.
Characters 74-75:
Warning: this match case is unused.
| one -> one
^^^
| j -> fib (j - 2) + fib (j - 1);;
^
val fib : int -> int = <fun>
# fib 1;;
- : int = 1
# fib 2002;;
- : int = 2002
This is a fairly common source of confusion. In essence you want to think of patterns as being built from constants (like
0and1) and identifiers that are bound by the pattern.When an identifier shows up in a pattern, it matches anything at all, and binds the matched value to the identifier. An identifier in a pattern does not refer to any previous value associated with the identifier. So, indeed, your pattern will always match the first case and bind
zeroto the value ofi.You could imagine that you’d like to be able to give names to constant values, then use the names rather than the constants in a pattern. However OCaml (like other FP languages) doesn’t work that way. One advantage (seems to me) is that it keeps things simple.