Version française
Home     About     Download     Resources     Contact us    
Browse thread
[Q] Multiple patterns in O'Caml
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: -- (:)
From: Matías Giovannini <matias@k...>
Subject: [Q] Multiple patterns in O'Caml
Hi, people.

I was wondering about multiple pattern matching using fun. Why is that,
compared to Caml Light, fun (unlike function) permits only one pattern
to be matched?
I'd think that, since type constructors and variables are in different
namespaces now, there would be no (syntactic) need for separate keywords
function and fun (as was true of Caml Light: fun couldn't distinguish
between a type constructor and a variable starting with an uppercase
letter in a pattern, hence it required every pattern to be parenthesized
to avoid ambiguities), and that fun could subsume the multiple-branch,
multiple-pattern of yore with the same elegant (and parentheses-sparing)
syntax of function.

Because, you see, I realize that the only way (other than to nest
match'es, or function's) to match multiple patterns is to use a tuple,
like this:

(* In Caml Light *)
let rec drop = fun
| 0 l -> l
| n [] -> failwith "drop"
| n (a::x) -> drop (pred n) x

(* In O'Caml *)
let rec drop n l = match (n,l) with
| 0,l -> l
| n,[] -> failwith "drop"
| n,a::x -> drop (pred n) x

but this requires an extraneous tuple construction and its subsequent
destruction, and kinda seems wasteful to me.

Thank you in advance, best regards