type pill = Red | Blue
let red = function
| Red -> "Kansas is going bye-bye"
| Blue -> "Bye!"
let blue pill = match pill with
| Red -> "Kansas is going bye-bye"
| Blue -> "Bye!"
Ocaml has the function and match with to do pattern matching. I always wondered on the why. Given, function is the short form (and only for single argument functions [see the naming gets weird here]), and it saves a few keystrokes, but why was it warranted to add to the language?
Which was first? Is this something that standard ML has early on? Im curious about the historic artefacts in ocaml and where they came from.
I may be wrong, but I have a vague feeling that it is the other way around: the shorthand is not function, but fun. In other words, function is the basic construction: “function of one argument defined by pattern matching” (remember that in Lambda calculus, all functions have exactly one argument), while fun x y z -> e is a shorthand for function x -> function y -> function z -> e.
In Caml Light (the predecessor of OCaml), the fun keyword could take multiple patterns (like OCaml’s function) as well as multiple arguments (like OCaml’s fun), but this introduced an ambiguity that required inserting parentheses around certain patterns. In the case of a single argument Caml Light also had function (like today’s OCaml), which did not suffer from this ambiguity. Since this issue with the extra parentheses was a bit bothersome, perhaps it was decided not to allow multiple patterns in the fun construct, and instead fall back on fun + match in that case.
@xavierleroy may be able to shed more light on this question.
I’m not sure this answers the original question, but:
The function/fun/match trilogy date back to the original CAML, as far as I can remember, then was reused in Caml Light and OCaml. As @nojb mentioned, Caml Light generalized fun to have multiple alternatives, but it was hard to use, so OCaml went back to the no-alternative fun that was already in CAML.
There is no doubt that these three constructs are redundant. CAML had function as the core notion (IIRC) and derived match and fun from there. OCaml has N-ary lambdas and a generalized match as the core notions, and derives fun and function from there.
Standard ML has fn (equivalent to OCaml’s function) as the core construct, and a derived case (OCaml’s match), plus a derived Haskell-style multiple-alternative multiple-parameter function declaration fun.
LCF ML, the common ancestor, had no user-defined datatypes and no pattern-matching, so no match and only lambda-abstractions.