On 20.05.2016 09:57, Soegtrop, Michael wrote:

Dear OCaml Users,

 

sometimes I want to do something like

 

match expr with

| case1 when cond1

| case2 when cond2

| case3 when cond3 -> result

 

but this doesn’t work. I have to write

 

match expr with

| case1 when cond1 -> result

| case2 when cond2 -> result

| case3 when cond3 -> result

 

Usually only some of the matches have a when clause. Is there a way to avoid copying the result term (other than writing a function) ?

 


I could not see a working web link to this old list message from 2016-04-07, so I just give you a copy of the answer by
Gabriel Scherer:

No, indeed you have to use a local definition to avoid code
duplication in this case.

My understanding of the design stance of pattern-matching in OCaml is
as follows: the syntax of patterns is bounded by what can be matched
efficiently. This explains why "when" has a second-class status
(first-class when cannot be matched efficiently); sometimes the user
has to pay for this rigidity. But, on the positive side, it is a
simple and clear stance, and it correlates with the availability of
good tooling, namely exhaustivity and useless-clause warnings.

On Thu, Apr 7, 2016 at 9:36 AM, Daniel Bünzli
<daniel.buenzli@erratique.ch> wrote:
Hello,

Something I run quite often is the following pattern matching

match v with
| None | Some c when sat c -> expr
| Some …

which doesn't compile and forces me to write

match v with
| None -> expr
| Some c when sat c -> expr
| Some …

and leads to code duplication or the introduction of a definition to avoid it.

Am I missing a syntax bit ?

Best,

Daniel