Reputation: 1829
I am following this OCaml tutorial.
They provided the two functions below and said that they are equivalent.
let string_of_int x = match x with
| 0 -> "zero"
| 1 -> "one"
| 2 -> "two"
| _ -> "many"
let string_of_int2 = function
| 0 -> "zero"
| 1 -> "one"
| 2 -> "two"
| _ -> "many"
My query is regarding the syntax of the above functions.
I wrote the same function but instead of | 0 ->
I simply did 0 ->
and the function still works in the same way. Is there any particular reason that the tutorial added the extra |
in their function?
In the second function what is the use of the function
keyword and why was this keyword absent in the first function?
Upvotes: 2
Views: 74
Reputation: 3847
Some people think it looks nicer and more organized, and it allows you to change the order of cases using cut & paste without having to worry about which one didn't have the |
.
The function
syntax is an abbreviation: function [CASES]
is the same as fun x -> match x with [CASES]
. There is a subtle difference, which is with function
it is not possible to shadow another variable by the name of the parameter.
let string_of_int x = [EXP]
is itself an abbreviation for let string_of_int = fun x -> [EXP]
.
So, to a close approximation, the "canonical" syntax uses fun
and match
, everything else is sugar. If you apply these two expansions to the two versions of the function, you will see that the same code results (modulo alpha-equivalence, of course :) ).
Upvotes: 3