let f i = match i with 1 -> "one" | 2 -> "two" | 3 -> "three" | x -> (string_of_int x)
When you are writing a function, and you need to do pattern matching on the last argument, there is a shortcut. You can automatically go into pattern matching mode for the last argument: So, this is equivalent to the above code:
let f = function 1 -> "one" | 2 -> "two" | 3 -> "three" | x -> (string_of_int x)
Understanding this pointless function is important. First, by using the
match keyword, you can essentially create en extended if statement. Notice how you can match specific things, like 1 and 2, and you can also match wildcards such as 'x'. In the example above, if the value of i is not 1, 2, or 3, then the value is bound to the variable 'x'. Then, x can be used freely.
The arguments to function are also patterns. This is perfectly legal:
# let factorial 5 = 120;; Characters 14-21: Warning: this pattern-matching is not exhaustive. Here is an example of a value that is not matched: 0 let factorial 5 = 120;; ^^^^^^^ val factorial : int -> int = <fun> # (factorial 5);; - : int = 120 # (factorial 4);; Exception: Match_failure ("", 16, -65).Now, you can put a wildcard pattern as the argument:
let factorial x = .....