tags:

views:

138

answers:

3

Is there a valid way to do the following in Haskell:

case n of
    0     -> doThis
    1     -> doThat
    2     -> doAnother
    3..99 -> doDefault

other than to have 97 lines of "doDefault" ?

+11  A: 
case n of
    0     -> doThis
    1     -> doThat
    2     -> doAnother
    _     -> doDefault

If you really need a range,

case n of
    0     -> doThis
    1     -> doThat
    2     -> doAnother
    x | 3 <= x && x < 100 -> doDefault
    _     -> reallyDoDefault
KennyTM
That's it. The second one. Thanks.
me2
MtnViewMark
A generalized form of that is in Data.Ix: case n of _ | inRange (3,100) n -> ...
Edward Kmett
+1  A: 

I think you can have the default case be the _ pattern, which matches on anything.

case n of
  0 -> doThis
  1 -> doThat
  2 -> doAnother
  _ -> doDefault

I'm not sure if that's quite what you're looking for, since it doesn't check the upper bound on the range there... you might want to use guards instead.

tredontho
+3  A: 

Using guards! ;)

Foo n 
  | n == 0 = doThis
  | n == 1 = doThat
  | n == 2 = doAnother
  | (n >= 3 ) && (n <= 99) = doDefault 


OR

  | n `elem` [3..99] =  doDefault
TheMachineCharmer
It should be `n == 0`, etc.
Alexey Romanov
Thanks! Alexey Romanov
TheMachineCharmer