Version française
Home     About     Download     Resources     Contact us    
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: -- (:)
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 caml-list-request@inria.fr Archives: http://caml.inria.fr
Bug reports: http://caml.inria.fr/bin/caml-bugs FAQ: http://caml.inria.fr/FAQ/
Beginner's list: http://groups.yahoo.com/group/ocaml_beginners