[Haskell-beginners] The case expression

David Morse dcmorse at gmail.com
Thu Jan 22 22:08:40 EST 2009


On Thu, Jan 22, 2009 at 10:01 PM, Erik de Castro Lopo
<mle+cl at mega-nerd.com> wrote:
>
> Hi all,
>
> Ocaml's match .. with expression (very similar to Haskell's case)
> allows multiple matches for a single result (naive example):
>
>    let f x =
>        match x with
>        | 0 -> "zero"
>        | 1 | 3 | 5 | 7 -> "odd"
>        | 2 | 4 | 6 | 8 -> "even"
>        _ -> "bad number"
>
> Is there a similar thing in Haskell? At the moment I have to do
> something like :
>
>    f x =
>        case x of
>          0 -> "zero"
>          1 -> "odd"
>          3 -> "odd"
>          5 -> "odd"
>          7 -> "odd"
>          2 -> "even"
>          4 -> "even"
>          6 -> "even"
>          8 -> "even"
>          _ -> "bad number"

Well you can guard each clause:

case x of
  0 -> "zero"
  n | even n -> "even"
     | odd n -> "odd"
     | otherwise -> "bad number"

Still not quite exactly what you've got.

So you could really hammer it with blunt force:

case x of
  0 -> "zero"
  n | n `elem` [1,3,5,7] -> "odd"
     | n `elem` [2, 4, 6, 8] -> "even"
     | otherwise -> "bad number"

By the way, zero is even. http://en.wikipedia.org/wiki/Zero_is_even


More information about the Beginners mailing list