Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the OCaml pattern `zero -> zero` seem to match everything?

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
like image 258
nerd cakez Avatar asked Jan 30 '12 02:01

nerd cakez


People also ask

What is pattern matching in OCaml?

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.

How do I match a string in OCaml?

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.

What does :: mean in OCaml?

If you have two variables called x and xs' then x :: xs' creates a new list with x prepended onto the front of xs' .

What is pattern matching in Haskell?

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.


1 Answers

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.

like image 149
Jeffrey Scofield Avatar answered Dec 17 '22 13:12

Jeffrey Scofield