[Haskell-beginners] Case Expressions
Brent Yorgey
byorgey at seas.upenn.edu
Thu May 28 18:27:31 EDT 2009
On Thu, May 28, 2009 at 05:53:43PM -0400, Nathan Holden wrote:
>
> interToBasic :: Interval -> BasicInterval
> interToBasic a = if (b == 1 || b == 2) then Second
> else if (b == 3 || b == 4) then Third
> ..
> where b = fromEnum a
>
> What I wanted to do, and figure is probably doable, but I can't seem to find
> it, is to say something like
>
> case (fromEnum a) of
> 1 || 2 -> Second
> 3 || 4 -> Third
> ..
>
> Is this doable? If so, what's the syntax?
You can do this with pattern guards, like so:
interToBasic a | b == 1 || b == 2 = Second
| b == 3 || b == 4 = Third
...
where b = fromEnum a
You could also use b `elem` [1,2] as an alternative to b == 1 || b ==
2 (especially nice when there are more than two options).
-Brent
More information about the Beginners
mailing list