[Haskell-beginners] Case statements shorter

Daniel Fischer daniel.is.fischer at web.de
Mon Nov 1 12:28:26 EDT 2010


On Monday 01 November 2010 16:59:33, Angel Alonso wrote:
> Hi,
>
> I have the following piece of code:
>
> n = 3
> case n of
>     3 -> "Something"
>     4 -> "Something"
>    _ -> "Other"
>
> Is it possible to shorten the case statement into something like this?:
>
> n = 3
> case n of
>     3 or 4 -> "Something"
>     _ -> "Other"

No, case does a pattern match. You can do

case n of
   _ | n `elem` [3,4] -> "Something"
     | otherwise -> "Other"

however, which becomes really useful if you have

case expression of
  pat1 | cond11 -> thing11
       | cond12 -> thing12
       | otherwise -> thing1Other
  pat2 | cond21 -> thing21
   ...

>
> Thanks.
>
> -- Angel Alonso



More information about the Beginners mailing list