[Haskell-beginners] Case statements shorter
uu1101 at gmail.com
uu1101 at gmail.com
Mon Nov 1 14:23:14 EDT 2010
> 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"
Is the following what you are looking for?
case n of
_ | n == 3 || n == 4 -> "something"
_ -> "other"
Some reminders:
* Guards are allowed in case expressions
* _ is not a special keyword in haskell. It's a regular variable so
will always match. It's usually used when you don't use it's value in
the right hand side or when it adds no information. In this case its
value will be n so there is no reason to introduce another name.
Also if you just have one special case you could use if then else:
if n == 3 || n ==4
then "something"
else "other"
Another solution is to take the common expression out. This is useful
if you are matching more complex structures in your case expression:
let st = "something"
in case n of
Left x | x == 3 || x == 4 -> st
Right _ -> st
_ -> "other"
Best regards.
More information about the Beginners
mailing list