Haskell guards on lambda functions?

20,742

Solution 1

As of GHC 7.6.1 there is an extension called MultiWayIf that lets you write the following:

\k -> if
  | k < 0     -> "negative"
  | k == 0    -> "zero"
  | otherwise -> "positive"

Which at the very least is more pleasant to look at than the alternative using case.

For pattern-matching, there is a related extension called LambdaCase:

\case
  "negative" -> -1
  "zero"     -> 0
  "positive" -> 1
  _          -> error "invalid sign"

These extensions are not part of standard Haskell, though, and need to be enabled explicitly via a {-# LANGUAGE LambdaCase #-} or {-# LANGUAGE MultiWayIf #-} pragma at the top of the file, or by compiling with the flag -XLambdaCase or -XMultiWayIf.

Solution 2

An elegant and concise way to do it with LambdaCase:

{-# LANGUAGE LambdaCase #-}

\case k | k < 0     -> "negative"
        | k == 0    -> "zero"
        | otherwise -> "positive"

or

\case
  k | k < 0     -> "negative"
    | k == 0    -> "zero"
    | otherwise -> "positive"

A case when I used it, to catch an EOF error:

{-# LANGUAGE ScopedTypeVariables #-}

o <- hGetContents e `catch` (\case (e :: IOException) | isEOFError e -> return "")
Share:
20,742
qrest
Author by

qrest

Updated on July 09, 2022

Comments

  • qrest
    qrest almost 2 years

    Is it possible to have guards on lambda functions?

    For example:

    \k
        | k < 0     -> "negative"
        | k == 0    -> "zero"
        | otherwise -> "positive"