3 Expressions
In this chapter, we describe the syntax and informal semantics of Haskell expressions, including their translations into the Haskell kernel, where appropriate. Except in the case of let expressions, these translations preserve both the static and dynamic semantics. Free variables and constructors used in these translations always refer to entities defined by the Prelude. For example, “concatMap” used in the translation of list comprehensions (Section 3.11) means the concatMap defined by the Prelude, regardless of whether or not the identifier “concatMap” is in scope where the list comprehension is used, and (if it is in scope) what it is bound to.
| (expression type signature) | |||
| (prefix negation) | |||
| (lambda abstraction, ) | |||
| (let expression) | |||
| (conditional) | |||
| (case expression) | |||
| (do expression) | |||
| (function application) | |||
| (variable) | |||
| (general constructor) | |||
| (parenthesized expression) | |||
| (tuple, ) | |||
| (list, ) | |||
| (arithmetic sequence) | |||
| (list comprehension, ) | |||
| (left section) | |||
| (right section) | |||
| (labeled construction, ) | |||
| (labeled update, ) |
Expressions involving infix operators are disambiguated by the operator’s fixity (see Section 4.4.2). Consecutive unparenthesized operators with the same precedence must both be either left or right associative to avoid a syntax error. Given an unparenthesized expression “” (where means an operator with associativity and precedence ), parentheses must be added around either or when unless or .
An example algorithm for resolving expressions involving infix operators is given in Section 10.6.
Negation is the only prefix operator in Haskell; it has the same precedence as the infix - operator defined in the Prelude (see Section 4.4.2, Figure 1).
The grammar is ambiguous regarding the extent of lambda abstractions, let expressions, and conditionals. The ambiguity is resolved by the meta-rule that each of these constructs extends as far to the right as possible.
Sample parses are shown below.
| This | Parses as |
|---|---|
f x + g y | (f x) + (g y) |
- f x + y | (- (f x)) + y |
let {...} in x + y | let {...} in (x + y) |
z + let {...} in x + y | z + (let {...} in (x + y)) |
f x y :: Int | (f x y) :: Int |
\ x -> a+b :: Int | \x -> ((a+b) :: Int) |
For the sake of clarity, the rest of this section will assume that expressions involving infix operators have been resolved according to the fixities of the operators.
3.1 Errors
Errors during expression evaluation, denoted by (“bottom”), are indistinguishable by a Haskell program from non-termination. Since Haskell is a non-strict language, all Haskell types include . That is, a value of any type may be bound to a computation that, when demanded, results in an error. When evaluated, errors cause immediate program termination and cannot be caught by the user. The Prelude provides two functions to directly cause such errors:
error :: String -> a
undefined :: aA call to error terminates execution of the program and returns an appropriate error indication to the operating system. It should also display the string in some system-dependent manner. When undefined is used, the error message is created by the compiler.
Translations of Haskell expressions use error and undefined to explicitly indicate where execution time errors may occur. The actual program behavior when an error occurs is up to the implementation. The messages passed to the error function in these translations are only suggestions; implementations may choose to display more or less information when an error occurs.
3.2 Variables, Constructors, Operators, and Literals
| (variable) | |||
| (general constructor) | |||
| (variable) | |||
| (qualified variable) | |||
| (constructor) | |||
| (qualified constructor) | |||
| (variable operator) | |||
| (qualified variable operator) | |||
| (constructor operator) | |||
| (qualified constructor operator) | |||
| (operator) | |||
| (qualified operator) | |||
Haskell provides special syntax to support infix notation. An operator is a function that can be applied using infix syntax (Section 3.4), or partially applied using a section (Section 3.5).
An operator is either an operator symbol, such as + or $$, or is an ordinary identifier enclosed in grave accents (backquotes), such as `op`. For example, instead of writing the prefix application op x y, one can write the infix application x `op` y. If no fixity declaration is given for op then it defaults to highest precedence and left associativity (see Section 4.4.2).
Dually, an operator symbol can be converted to an ordinary identifier by enclosing it in parentheses. For example, (+) x y is equivalent to x + y, and foldr (*) 1 xs is equivalent to foldr (\x y -> x*y) xs.
Special syntax is used to name some constructors for some of the built-in types, as found in the production for and . These are described in Section 6.1.
An integer literal represents the application of the function fromInteger to the appropriate value of type Integer. Similarly, a floating point literal stands for an application of fromRational to a value of type Rational (that is, Ratio Integer).
Translation: The integer literal is equivalent to , where fromInteger is a method in class Num (see Section 6.4.1).
The floating point literal is equivalent to , where fromRational is a method in class Fractional and Ratio.% constructs a rational from two integers, as defined in the module Data.Ratio from the standard library. The integers and are chosen so that .
3.3 Curried Applications and Lambda Abstractions
| (function application) | |||
| (lambda abstraction ) |
Function application is written . Application associates to the left, so the parentheses may be omitted in (f x) y. Because could be a data constructor, partial applications of data constructors are allowed.
Lambda abstractions are written , where the are patterns. An expression such as \x:xs->x is syntactically incorrect; it may legally be written as \(x:xs)->x.
The set of patterns must be linear—no variable may appear more than once in the set.
Translation: The following identity holds:
where the are new identifiers.
Given this translation combined with the semantics of case expressions and pattern matching described in Section 3.18.4, if the pattern fails to match, then the result is .
3.4 Operator Applications
| (prefix negation) | |||
| (qualified operator) |
The form is the infix application of binary operator to expressions and .
The special form denotes prefix negation, the only prefix operator in Haskell, and is syntax for . The binary - operator does not necessarily refer to the definition of - in the Prelude; it may be rebound by the module system. However, unary - will always refer to the negate function defined in the Prelude. There is no link between the local meaning of the - operator and unary negation.
Prefix negation has the same precedence as the infix operator - defined in the Prelude (see Table 1). Because e1-e2 parses as an infix application of the binary operator -, one must write e1(-e2) for the alternative parsing. Similarly, (-) is syntax for \x y -> x-y, as with any infix operator, and does not denote \x -> -x—one must use negate for that.
Translation: The following identities hold:
3.5 Sections
| (left section) | |||
| (right section) |
Sections are written as or , where is a binary operator and is an expression. Sections are a convenient syntax for partial application of binary operators.
Syntactic precedence rules apply to sections as follows. is legal if and only if parses in the same way as ; and similarly for . For example, (*a+b) is syntactically invalid, but (+a*b) and (*(a+b)) are valid. Because (+) is left associative, (a+b+) is syntactically correct, but (+a+b) is not; the latter may legally be written as (+(a+b)). As another example, the expression
(let n = 10 in n +)is invalid because, by the let/lambda meta-rule (Section 3), the expression
(let n = 10 in n + x)parses as
(let n = 10 in (n + x))rather than
((let n = 10 in n) + x)Because - is treated specially in the grammar, is not a section, but an application of prefix negation, as described in the preceding section. However, there is a subtract function defined in the Prelude such that is equivalent to the disallowed section. The expression can serve the same purpose.
Translation: The following identities hold:
where is a binary operator, is an expression, and is a variable that does not occur free in .
3.6 Conditionals
A conditional expression has the form and returns the value of if the value of is True, if is False, and otherwise.
Translation: The following identity holds:
where True and False are the two nullary constructors from the type Bool, as defined in the Prelude. The type of must be Bool; and must have the same type, which is also the type of the entire conditional expression.
3.7 Lists
Lists are written , where . The list constructor is :, and the empty list is denoted []. Standard operations on lists are given in the Prelude (see Section 6.1.3, and Chapter 9 notably Section 9.1).
Translation: The following identity holds:
where : and [] are constructors for lists, as defined in the Prelude (see Section 6.1.3). The types of through must all be the same (call it ), and the type of the overall expression is [t] (see Section 4.1.2).
The constructor “:” is reserved solely for list construction; like [], it is considered part of the language syntax, and cannot be hidden or redefined. It is a right-associative operator, with precedence level 5 (Section 4.4.2).
3.8 Tuples
Tuples are written , and may be of arbitrary length . The constructor for an -tuple is denoted by , where there are commas. Thus (a,b,c) and (,,) a b c denote the same value. Standard operations on tuples are given in the Prelude (see Section 6.1.4 and Chapter 9).
3.9 Unit Expressions and Parenthesized Expressions
The form ) is simply a parenthesized expression, and is equivalent to . The unit expression () has type () (see Section 4.1.2). It is the only member of that type apart from , and can be thought of as the “nullary tuple” (see Section 6.1.5).
3.10 Arithmetic Sequences
The arithmetic sequence denotes a list of values of type , where each of the has type , and is an instance of class Enum.
Translation: Arithmetic sequences satisfy these identities:
[ ..] | enumFrom | |
[ , ..] | enumFromThen | |
[ .. ] | enumFromTo | |
[ , .. ] | enumFromThenTo |
where enumFrom, enumFromThen, enumFromTo, and enumFromThenTo are class methods in the class Enum as defined in the Prelude (see Section 6.3.4).
The semantics of arithmetic sequences therefore depends entirely on the instance declaration for the type t. See Section 6.3.4 for more details of which Prelude types are in Enum and their semantics.
3.11 List Comprehensions
| (list comprehension, ) | |||
| (generator) | |||
| (local declaration) | |||
| (boolean guard) |
A list comprehension has the form , , where the qualifiers are either
- generators of the form , where is a pattern (see Section 3.18) of type and is an expression of type
- local bindings that provide new definitions for use in the generated expression or subsequent boolean guards and generators
- boolean guards, which are arbitrary expressions of type
Bool.
Such a list comprehension returns the list of elements produced by evaluating in the successive environments created by the nested, depth-first evaluation of the generators in the qualifier list. Binding of variables occurs according to the normal pattern matching rules (see Section 3.18), and if a match fails then that element of the list is simply skipped over. Thus:
[ x | xs <- [ [(1,2),(3,4)], [(5,4),(3,2)] ],
(3,x) <- xs ]yields the list [4,2]. If a qualifier is a boolean guard, it must evaluate to True for the previous pattern match to succeed. As usual, bindings in list comprehensions can shadow those in outer scopes; for example:
Translation: List comprehensions satisfy these identities, which may be used as a translation into the kernel:
where ranges over expressions, over patterns, over list-valued expressions, over boolean expressions, over declaration lists, over qualifiers, and over sequences of qualifiers. ok is a fresh variable. The function concatMap, and boolean value True, are defined in the Prelude.
As indicated by the translation of list comprehensions, variables bound by let have fully polymorphic types while those defined by <- are lambda bound and are thus monomorphic (see Section 4.5.4).
3.12 Let Expressions
Let expressions have the general form , and introduce a nested, lexically-scoped, mutually-recursive list of declarations (let is often called letrec). The scope of the declarations is the expression and the right hand side of the declarations. Declarations are described in Chapter 4. Pattern bindings are matched lazily; an implicit ~ makes these patterns irrefutable. For example,
does not cause an execution-time error until x or y is evaluated.
Translation: The dynamic semantics of the expression are captured by this translation: After removing all type signatures, each declaration is translated into an equation of the form , where and are patterns and expressions respectively, using the translation in Section 4.4.3. Once done, these identities hold, which may be used as a translation into the kernel:
| where no variable in appears free in | ||
where fix is the least fixpoint operator. Note the use of the irrefutable patterns ~p. This translation does not preserve the static semantics because the use of case precludes a fully polymorphic typing of the bound variables. The static semantics of the bindings in a let expression are described in Section 4.4.3.
3.13 Case Expressions
| (empty alternative) | |||
| (pattern guard) | |||
| (local declaration) | |||
| (boolean guard) |
A case expression has the general form
where each is of the general form
(Notice that in the syntax rule for , the “|” is a terminal symbol, not the syntactic metasymbol for alternation.) Each alternative consists of a pattern and its matches, . Each match in turn consists of a sequence of pairs of guards and bodies (expressions), followed by optional bindings () that scope over all of the guards and expressions of the alternative.
A guard has one of the following forms:
- pattern guards are of the form , where is a pattern (see Section 3.18) of type and is an expression type . They succeed if the expression matches the pattern , and introduce the bindings of the pattern to the environment.
- local bindings are of the form . They always succeed, and they introduce the names defined in to the environment.
- boolean guards are arbitrary expressions of type
Bool. They succeed if the expression evaluates toTrue, and they do not introduce new names to the environment. A boolean guard, , is semantically equivalent to the pattern guard .
An alternative of the form
is treated as shorthand for:
A case expression must have at least one alternative and each alternative must have at least one body. Each body must have the same type, and the type of the whole expression is that type.
A case expression is evaluated by pattern matching the expression against the individual alternatives. The alternatives are tried sequentially, from top to bottom. If matches the pattern of an alternative, then the guarded expressions for that alternative are tried sequentially from top to bottom in the environment of the case expression extended first by the bindings created during the matching of the pattern, and then by the in the where clause associated with that alternative.
For each guarded expression, the comma-separated guards are tried sequentially from left to right. If all of them succeed, then the corresponding expression is evaluated in the environment extended with the bindings introduced by the guards. That is, the bindings that are introduced by a guard (either by using a let clause or a pattern guard) are in scope in the following guards and the corresponding expression. If any of the guards fail, then this guarded expression fails and the next guarded expression is tried.
If none of the guarded expressions for a given alternative succeed, then matching continues with the next alternative. If no alternative succeeds, then the result is . Pattern matching is described in Section 3.18, with the formal semantics of case expressions in Section 3.18.4.
A note about parsing. The expression
case x of { (a,_) | let b = not a in b :: Bool -> a }is tricky to parse correctly. It has a single unambiguous parse, namely
case x of { (a,_) | (let b = not a in b :: Bool) -> a }However, the phrase Bool -> a is syntactically valid as a type, and parsers with limited lookahead may incorrectly commit to this choice, and hence reject the program. Programmers are advised, therefore, to avoid guards that end with a type signature — indeed that is why a contains an not an .
3.14 Do Expressions
| (do expression) | |||
| (empty statement) |
A do expression provides a more conventional syntax for monadic programming. It allows an expression such as
putStr "x: " >>
getLine >>= \l ->
return (words l)to be written in a more traditional way as:
do putStr "x: "
l <- getLine
return (words l)Translation: Do expressions satisfy these identities, which may be used as a translation into the kernel, after eliminating empty :
The ellipsis “...” stands for a compiler-generated error message, passed to fail, preferably giving some indication of the location of the pattern-match failure; the functions >>, >>=, and fail are operations in the class Monad, as defined in the Prelude; and ok is a fresh identifier.
As indicated by the translation of do, variables bound by let have fully polymorphic types while those defined by <- are lambda bound and are thus monomorphic.
3.15 Datatypes with Field Labels
A datatype declaration may optionally define field labels (see Section 4.2.1). These field labels can be used to construct, select from, and update fields in a manner that is independent of the overall structure of the datatype.
Different datatypes cannot share common field labels in the same scope. A field label can be used at most once in a constructor. Within a datatype, however, a field label can be used in more than one constructor provided the field has the same typing in all constructors. To illustrate the last point, consider:
data S = S1 { x :: Int } | S2 { x :: Int } -- OK
data T = T1 { y :: Int } | T2 { y :: Bool } -- BADHere S is legal but T is not, because y is given inconsistent typings in the latter.
3.15.1 Field Selection
Field labels are used as selector functions. When used as a variable, a field label serves as a function that extracts the field from an object. Selectors are top level bindings and so they may be shadowed by local variables but cannot conflict with other top level bindings of the same name. This shadowing only affects selector functions; in record construction (Section 3.15.2) and update (Section 3.15.3), field labels cannot be confused with ordinary variables.
Translation: A field label introduces a selector function defined as:
where are all the constructors of the datatype containing a field labeled with , is when labels the th component of or otherwise, and is when some field in has a label of or undefined otherwise.
3.15.2 Construction Using Field Labels
| (labeled construction, ) | |||
A constructor with labeled fields may be used to construct a value in which the components are specified by name rather than by position. Unlike the braces used in declaration lists, these are not subject to layout; the { and } characters must be explicit. (This is also true of field updates and field patterns.) Construction using field labels is subject to the following constraints:
- Only field labels declared with the specified constructor may be mentioned.
- A field label may not be mentioned more than once.
- Fields not mentioned are initialized to .
- A compile-time error occurs when any strict fields (fields whose declared types are prefixed by
!) are omitted during construction. Strict fields are discussed in Section 4.2.1.
The expression F {}, where F is a data constructor, is legal whether or not F was declared with record syntax (provided F has no strict fields — see the fourth bullet above); it denotes , where is the arity of F.
Translation: In the binding , the field labels .
where is the arity of .
The auxiliary function is defined as follows:
If the th component of a constructor has the field label , and if appears in the binding list , then is . Otherwise, is the default value .
3.15.3 Updates Using Field Labels
| (labeled update, ) |
Values belonging to a datatype with field labels may be non-destructively updated. This creates a new value in which the specified field values replace those in the existing value. Updates are restricted in the following ways:
- All labels must be taken from the same datatype.
- At least one constructor must define all of the labels mentioned in the update.
- No label may be mentioned more than once.
- An execution error occurs when the value being updated does not contain all of the specified labels.
Translation: Using the prior definition of ,
where is the set of constructors containing all labels in , and is the arity of .
Here are some examples using labeled fields:
data T = C1 {f1,f2 :: Int}
| C2 {f1 :: Int,
f3,f4 :: Char}| Expression | Translation |
|---|---|
C1 {f1 = 3} | C1 3 undefined |
C2 {f1 = 1, f4 = 'A', f3 = 'B'} | C2 1 'B' 'A' |
x {f1 = 1} | case x of C1 _ f2 -> C1 1 f2 |
C2 _ f3 f4 -> C2 1 f3 f4 |
The field f1 is common to both constructors in T. This example translates expressions using constructors in field-label notation into equivalent expressions using the same constructors without field labels. A compile-time error will result if no single constructor defines the set of field labels used in an update, such as x {f2 = 1, f3 = 'x'}.
3.16 Expression Type-Signatures
Expression type-signatures have the form , where is an expression and is a type (Section 4.1.2); they are used to type an expression explicitly and may be used to resolve ambiguous typings due to overloading (see Section 4.3.4). The value of the expression is just that of . As with normal type signatures (see Section 4.4.1), the declared type may be more specific than the principal type derivable from , but it is an error to give a type that is more general than, or not comparable to, the principal type.
Translation:
3.17 Patterns
This section introduces the syntax of patterns (Section 3.17.1) and some of their important properties: Linearity (Section 3.17.2), refutability (Section 3.17.3) and failability (Section 3.17.4). The semantics of patterns in the context of case expressions, and how to evaluate them, is discussed in Section 3.18.
3.17.1 Syntax
Patterns have this syntax:
| (infix constructor) | |||
| (negative literal) | |||
| (arity , ) | |||
| (as pattern) | |||
| (arity ) | |||
| (labeled pattern, ) | |||
| (wildcard) | |||
| (parenthesized pattern) | |||
| (tuple pattern, ) | |||
| (list pattern, ) | |||
| (irrefutable pattern) | |||
3.17.1.1 As-Patterns
Patterns of the form are called as-patterns, and allow one to use as a name for the value being matched by . For example,
case e of { xs@(x:rest) -> if x==0 then rest else xs }is equivalent to:
let { xs = e } in
case xs of { (x:rest) -> if x==0 then rest else xs }3.17.1.2 Wildcard Patterns
Patterns of the form _ are wildcards and are useful when some part of a pattern is not referenced on the right-hand-side. It is as if an identifier not used elsewhere were put in its place. For example,
case e of { [x,_,_] -> if x==0 then True else False }is equivalent to:
case e of { [x,y,z] -> if x==0 then True else False }3.17.1.3 Numeric Literal Patterns
Aside from the obvious static type constraints (for example, it is a static error to match a character against a boolean), the following static class constraints hold:
- An integer literal pattern can only be matched against a type that is an instance of classes
NumandEq. - A floating literal pattern can only be matched against a type that is an instance of classes
FractionalandEq.
3.17.2 Linear Patterns
A pattern is linear if no variable appears more than once in it.
All patterns must be linear. For example, this definition is illegal:
f (x,x) = x -- ILLEGAL; x used twice in pattern3.17.3 Refutable and Irrefutable Patterns
Every pattern is either refutable or irrefutable. The irrefutable patterns are as follows:
- a variable
- a wildcard
- where is a constructor defined by
newtypeand is irrefutable (see Section 4.2.3) - where is irrefutable,
- (whether or not is irrefutable).
All other patterns are refutable.
Refutability is a syntactic property that can be checked by inspecting the syntax of the pattern and consulting type declarations in the program. However, it is motivated by the following semantic property: Matching an irrefutable pattern is non-strict: the pattern matches even if the value to be matched is . Matching an irrefutable pattern against a value can therefore never diverge or fail (cp. Section 3.18.1). Matching a refutable pattern is strict: if the value to be matched is the match diverges.
3.17.4 Failable and Failure-Free Patterns
Every pattern is either failable or failure-free. The failure-free patterns are as follows:
- a variable
- a wildcard
- where is a constructor defined by
newtypeand is failure-free (see Section 4.2.3) - where is the only constructor defined by a
datadeclaration and to are all failure-free. - where is failure-free,
- (whether or not is failure-free).
All other patterns are failable.
Every irrefutable pattern is also failure-free, but not vice-versa: for example (x, y) is failure-free but refutable.
Failability is a syntactic property that can be checked by inspecting the syntax of the pattern and consulting type declarations in the program. However, it is motivated by the following semantic property: Matching a failure-free pattern against a value can never fail (cp. Section 3.18.1).
3.18 Pattern Matching
Patterns appear in lambda abstractions, function definitions, pattern bindings, list comprehensions, do expressions, and case expressions. However, the first five of these ultimately translate into case expressions, so defining the semantics of pattern matching for case expressions is sufficient.
3.18.1 Outcomes of Matching a Pattern Against a Value
Patterns are matched against values, which can have one of three results:
- it may fail. For example, matching the pattern
Trueagainst the valueFalsefails. - it may succeed, returning a binding for each variable in the pattern. For example, matching the pattern
[x,y]against the value[2,3]succeeds and bindsxto the value2andyto the value3. - it may diverge. For example, matching the pattern
Trueagainst the value diverges. In that case the overall computation of which the pattern is a part also diverges (i.e. returns ).
3.18.2 Informal Semantics of Pattern Matching
Pattern matching proceeds from left to right, and outside to inside, according to the following rules:
- Matching the pattern against a value always succeeds and binds to .
Matching the pattern against a value always succeeds. The free variables in are bound to the appropriate values if matching against would otherwise succeed, and to if matching against fails or diverges. (Binding does not imply evaluation.)
Operationally, this means that no matching is done on a pattern until one of the variables in is used. At that point the entire pattern is matched against the value, and if the match fails or diverges, so does the overall computation.
- Matching the wildcard pattern
_against any value always succeeds, and no binding is done. Matching the pattern against a value, where is a constructor defined by
newtype, depends on the value:- If the value is of the form , then is matched against .
- If the value is , then is matched against .
That is, constructors associated with
newtypeserve only to change the type of a value.Matching the pattern against a value, where is a constructor defined by
data, depends on the value:- If the value is of the form , sub-patterns are matched left-to-right against the components of the data value; if all matches succeed, the overall match succeeds; the first to fail or diverge causes the overall match to fail or diverge, respectively.
- If the value is of the form , where is a different constructor to , the match fails.
- If the value is , the match diverges.
- Matching against a constructor using labeled fields is the same as matching ordinary constructor patterns except that the fields are matched in the order they are named in the field list. All fields listed must be declared by the constructor; fields may not be named more than once. Fields not named by the pattern are ignored (matched against
_). Matching a numeric, character, or string literal pattern against a value succeeds if , where
==is overloaded based on the type of the pattern. The match diverges if this test diverges.The interpretation of numeric literals is exactly as described in Section 3.2; that is, the overloaded function
fromIntegerorfromRationalis applied to anIntegerorRationalliteral (resp) to convert it to the appropriate type.- Matching an as-pattern against a value is the result of matching against , augmented with the binding of to . If the match of against fails or diverges, then so does the overall match.
3.18.2.1 Examples
If the pattern
['a','b']is matched against , then'a'fails to match against'x', and the result is a failed match. But if['a','b']is matched against , then attempting to match'a'against causes the match to diverge.These examples demonstrate refutable vs. irrefutable (Section 3.17.3) matching:
(\ ~(x,y) -> 0)(\ (x,y) -> 0)(\ ~[x] -> 0) [](\ ~[x] -> x) [](\ ~[x, ~(a,b)] -> x(\ ~[x, (a,b)] -> x(\ (x:xs) -> x:x:xs)(\ ~(x:xs) -> x:x:xs)Consider the following declarations:
newtype N = N Bool data D = D !BoolThese examples illustrate the difference in pattern matching between types defined by
dataandnewtype:(\ (N True) -> True)(\ (D True) -> True)(\ ~(D True) -> True)TrueAdditional examples may be found in Section 4.2.3.
3.18.3 Guards
Top level patterns in case expressions and the set of top level patterns in function or pattern bindings may have zero or more associated guards. See Section 3.13 for the syntax and semantics of guards.
The guard semantics have an influence on the strictness characteristics of a function or case expression. In particular, an otherwise irrefutable pattern may be evaluated because of a guard. For example, in
f :: (Int,Int,Int) -> [Int] -> Int
f ~(x,y,z) [a] | (a == y) = 1both a and y will be evaluated by == in the guard.
3.18.4 Formal Semantics of Pattern Matching
The semantics of all pattern matching constructs other than case expressions are defined by giving identities that relate those constructs to case expressions. The semantics of case expressions themselves are in turn given as a series of identities, in Figure 1 – Figure 2. Any implementation should behave so that these identities hold; it is not expected that it will use them directly, since that would generate rather inefficient code.
In Figure 1 – Figure 2: , and are expressions; and are guards and sequences of guards respectively; and are patterns; , , and are variables; and are algebraic datatype (data) constructors (including tuple constructors); and is a newtype constructor.
Rule (b) matches a general source-language case expression, regardless of whether it actually includes guards—if no guards are written, then True is substituted for the guards in the forms. Subsequent identities manipulate the resulting case expression into simpler and simpler forms.
Rule (h) in Listing 3 involves the overloaded operator ==; it is this rule that defines the meaning of pattern matching against overloaded constants.
These identities all preserve the static semantics. Rules (d), (e), (j), and (q) use a lambda rather than a let; this indicates that variables bound by case are monomorphically typed (Section 4.1.4).
- (a)
where is a new variable- (b)
where each has the form- (c)
where is a new variable- (d)
where are all the variables in- (e)
- (f)
- (g)
at least one of is not a variable; are new variables- (h)
where is a numeric, character, or string literal- (i)
- (j)
- (k)
where is anewtypeconstructor- (l)
where is a newtype constructor- (m)
where are fields of constructor ; is a new variable- (n)
where is if labels the th component of ,_otherwise- (o)
- (p)
where and are distinctdataconstructors of arity and , respectively- (q)
where is adataconstructor of arity- (r)
where is adataconstructor of arity
- (s)
where is a new variable- (t)
- (u)
- (v)