Difference between revisions of "Pattern guard"
Jump to navigation
Jump to search
BrettGiles (talk | contribs) (HaWiki conversion) |
(Changed introduction to mention Haskell 2010; corrected links, added link to the Haskell Prime wiki page of Pattern Guards) |
||
(4 intermediate revisions by 2 users not shown) | |||
Line 1: | Line 1: | ||
⚫ | Haskell 2010 changes the syntax for [[guard]]s 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. |
||
⚫ | |||
− | |||
⚫ | |||
Stealing a function from the note, |
Stealing a function from the note, |
||
Line 14: | Line 12: | ||
==See also== |
==See also== |
||
− | *[http://research.microsoft.com/ |
+ | *[http://research.microsoft.com/en-us/um/people/simonpj/Haskell/guards.html Simon Peyton Jones' note] on pattern guards |
− | *[http://research.microsoft.com/ |
+ | *[http://research.microsoft.com/en-us/um/people/simonpj/Papers/pat.htm Pattern Guards and Transformational Patterns]. |
+ | *[http://www.haskell.org/ghc/docs/latest/html/users_guide/syntax-extns.html#pattern-guards GHC Manual on pattern guards] |
||
+ | * [http://hackage.haskell.org/trac/haskell-prime/wiki/PatternGuards#BriefExplanation The Haskell Prime wiki page of Pattern Guards] |
||
+ | |||
⚫ | |||
+ | [[Category:Language extensions]] |
||
+ | [[Category:Syntax]] |
Revision as of 21:27, 24 November 2009
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.
Stealing a function from the note,
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.