Pattern guard

From HaskellWiki
Revision as of 14:53, 7 September 2016 by Nomeata (talk | contribs) (→‎See also)
Jump to navigation Jump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

Haskell 2010 changes the syntax for guards by replacing the use of a single condition with a list of qualifiers. These qualifiers, which include both conditions and pattern guards of the form pat <- exp, serve to bind/match patterns against expressions. The syntax is comparable that of a list comprehension, where instead the types of pat and exp match. This makes it easy, for instance, to pattern match against (possibly failing) table lookups while deciding which definition of a function to use.

From the GHC user's guide,

lookup :: FiniteMap -> Int -> Maybe Int

addLookup env var1 var2
   | Just val1 <- lookup env var1
   , Just val2 <- lookup env var2
   = val1 + val2
{-...other equations...-}

will check to see if both lookups succeed, and bind the results to val1 and val2 before proceeding to use the equation.

See also