
On Wed, Nov 10, 2010 at 09:58:15PM +0100, Daniel Fischer wrote:
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 ...
Yes, and doing it this way obviates the need for a case expression: map f list where f [] = ... f [y] | y < 5 = ...
Is it considered bad form?
Using patterns and guards in case expressions isn't necessarily bad form. But it doesn't seem to be that common. -Brent