[Haskell-beginners] What is the Haskell idiom for "if then else
if then"
Daniel Fischer
daniel.is.fischer at web.de
Mon Mar 30 11:50:20 EDT 2009
Am Montag 30 März 2009 17:33:02 schrieb Peter Hickman:
> I've just written this piece of code
>
> if r < 0
> then LEFT
> else
> if r > 0
> then RIGHT
> else STRAIGHT
>
> which works just fine but it does look rather clunky (as it would in
> any language I suppose). Is there a Haskell idiom for this type of code?
Usually, people use guards:
function r
| r < 0 = LEFT
| r > 0 = RIGHT
| otherwise = STRAIGHT
Another option would be a case:
case compare r 0 of
LT -> LEFT
GT -> RIGHT
EQ -> STRAIGHT
You can also have a case with guards:
case expression of
pattern1 | condition1.1 -> result1.1
| condition1.2 -> result1.2
pattern2 | condition2.1 -> result2.1
pattern3 -> result3
_ -> defaultresult
More information about the Beginners
mailing list