[Haskell-beginners] case as guards in lambda functions

Daniel Fischer daniel.is.fischer at web.de
Wed Nov 10 15:58:15 EST 2010


On Wednesday 10 November 2010 21:13:26, Russ Abbott wrote:
> I have often wanted to use a guard in a lambda function and had thought
> it wasn't possible. But apparently the case construct allows a viable
> approach. Here is a silly example.
>
> testCase = map
>              (\xs -> case xs of
>                      []              -> "empty list"
>                      [y] | y < 5     -> "small singleton"
>
>                          | otherwise -> "large singleton"
>
>                      _               -> "multi-element list")
>
> > testCase [[], [2], [7], [1,2,3]]
>
> ["empty","small singleton","large singleton","multi-element list"]
>
> It seems particularly useful to be able to include both patterns and
> guards in case expressions. I haven't seen this usage anywhere.

If it's not a very small case-expression, usually one puts it in a where 
clause,

map f list
  where
    f xs = case xs of
             ...

since a huge lambda expression tends to obscure the overall structure of 
the expression.


> Is it considered bad form?

If the expression becomes too large.

> *
> -- Russ *



More information about the Beginners mailing list