tags:

views:

162

answers:

2

Is it possible to have guards on lambda functions?

For example:

\k
    | k < 0     -> "negative"
    | k == 0    -> "zero"
    | otherwise -> "positive"
+9  A: 

Nope. The nearest direct translation is something a bit like

\k -> case () of
       _ | k < 0     -> "negative"
         | k == 0    -> "zero"
         | otherwise -> "positive"
Ganesh Sittampalam
Never thought of using `_` over `()` :D
trinithis
You can use it over anything, of course, but `()` is short and probably least confusing.
Ganesh Sittampalam
+6  A: 

I like to keep lambdas short and sweet so as not to break the reader's visual flow. For a function whose definition is syntactically bulky enough to warrant guards, why not stick it in a where clause?

showSign k = mysign ++ " (" ++ show k ++ ")"
  where
  mysign
    | k < 0     = "negative"
    | k == 0    = "zero"
    | otherwise = "positive"
Greg Bacon