Tuesday, 1 December 2009

A Haskell Mini-Pattern

Rightly or wrongly, I found myself writing code like this:


foo :: [Bar] -> [Baz]
foo xs = if (any f xs) then [] else [Baz 4]


This can be replaced with a neater list comprehension


[Baz 4 | any f xs]


If the right hand side of the list comprehension evaluation to false, then you get the empty list, else you get the single item in the list.

Neat, though I've no idea whether it's idiomatic Haskell!