[Haskell-beginners] The case expression

Brent Yorgey byorgey at seas.upenn.edu
Thu Jan 22 22:11:20 EST 2009


On Fri, Jan 23, 2009 at 02:01:41PM +1100, Erik de Castro Lopo 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? 

There isn't, but in this particular case (and in many similar cases)
you could always do something like this, using guards:

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

-Brent


More information about the Beginners mailing list