# What is the Haskell idiom for "if then else if then"

4 messages
Open this post in threaded view
|

## What is the Haskell idiom for "if then else if then"

 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?
Open this post in threaded view
|

## What is the Haskell idiom for "if then else if then"

 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