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
Pattern matching comes up in several places in OCaml: as a powerful control structure combining a multi-armed conditional, unification, data destructuring and variable binding; as a shortcut way of defining functions by case analysis; and as a way of handling exceptions.
There is a way to match strings as a list of characters, using a function from SML (which you can write in OCaml) called 'explode' and 'implode' which --respectively -- take a string to a char list and vice versa.
If you have two variables called x and xs' then x :: xs' creates a new list with x prepended onto the front of xs' .
Pattern matching consists of specifying patterns to which some data should conform and then checking to see if it does and deconstructing the data according to those patterns. When defining functions, you can define separate function bodies for different patterns.
This is a fairly common source of confusion. In essence you want to think of patterns as being built from constants (like 0
and 1
) 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 zero
to the value of i
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With