Version française
Home     About     Download     Resources     Contact us    

This site is updated infrequently. For up-to-date information, please visit the new OCaml website at

Browse thread
[Caml-list] Guards vs. conditionals
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 2003-01-02 (09:54)
From: Xavier Leroy <xavier.leroy@i...>
Subject: Re: [Caml-list] Guards vs. conditionals
> I'm just curious about something. I've been noticing that in many cases
> (if not always) a pattern match with guard expressions in OCaml is
> equivalent to a conditional statement.

Not always strictly equivalent.  Consider

  match x with hd::tl when hd <> 0 -> <expr1>
             | _ -> <expr2>

Without "when", you'd need to duplicate <expr2>:

  match x with hd::tl -> if hd <> 0 then <expr1> else <expr2>
             | _ -> <expr2>

> So, my question is, is there any objective reason to prefer the
> pattern-match version over the conditional, or vice versa? Or is it just
> a matter of coding style?

It's just a question of style.  Personally, I'd recommend using "when"
in cases where "real" pattern-matching is involved, as in the example
above, and cascades of "if...then...else..." in cases where it doesn't
cause duplication of code.  But you can opt for a different style.

- Xavier Leroy
To unsubscribe, mail Archives:
Bug reports: FAQ:
Beginner's list: