[Haskell-beginners] The case expression

Daniel Seidel seideld at tcs.inf.tu-dresden.de
Fri Jan 23 02:41:27 EST 2009


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? 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"
>
> Cheers,
> Erik
>   
Hi Erik,

you can use guards like this:

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

daniel.
-------------- next part --------------
A non-text attachment was scrubbed...
Name: seideld.vcf
Type: text/x-vcard
Size: 255 bytes
Desc: not available
Url : http://www.haskell.org/pipermail/beginners/attachments/20090123/0e2b5837/seideld-0001.vcf


More information about the Beginners mailing list