exps.verb 55.5 KB
Newer Older
Simon Peyton Jones's avatar
Simon Peyton Jones committed
1
%
Simon Peyton Jones's avatar
Simon Peyton Jones committed
2
% $Header: /home/cvs/root/haskell-report/report/exps.verb,v 1.14 2001/12/21 16:00:24 simonpj Exp $
Simon Peyton Jones's avatar
Simon Peyton Jones committed
3
4
5
6
7
8
9
%
%*section 3
%**<title>The Haskell 98 Report: Expressions</title>
%**~header
\section{Expressions}\index{expression}
\label{expressions}

Simon Peyton Jones's avatar
Simon Peyton Jones committed
10
11
In this section, we describe the syntax and informal semantics of
\Haskell{} {\em expressions}, including their translations into the
Simon Peyton Jones's avatar
Simon Peyton Jones committed
12
13
\Haskell{} kernel, where appropriate.  Except in the case of @let@
expressions, these translations preserve both the static and dynamic
Simon Peyton Jones's avatar
Simon Peyton Jones committed
14
15
16
17
18
19
20
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~\ref{list-comprehensions}) 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.
Simon Peyton Jones's avatar
Simon Peyton Jones committed
21

Simon Peyton Jones's avatar
Simon Peyton Jones committed
22
23
24
25
26
27
In the syntax that follows, there are some families of nonterminals
indexed by precedence levels (written as a superscript).  Similarly, the
nonterminals "op", "varop", and "conop" may have a double index:
a letter "l", "r", or "n" for left-, right- or non-associativity and
a precedence level.  A precedence-level variable "i" ranges from 0 to 9;
an associativity variable "a" varies over "\{l, r, n\}".
28
For example
Simon Peyton Jones's avatar
Simon Peyton Jones committed
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
@@@
aexp	->  @(@ exp^{i+1} qop^{(a,i)} @)@
@@@
actually stands for 30 productions, with 10 substitutions for "i"
and 3 for "a".

@@@
exp	->  exp^0 @::@ [context @=>@] type	& (\tr{expression type signature})
        |   exp^0
exp^i	->  exp^{i+1} [qop^{({\rm{n}},i)} exp^{i+1}]
	|   lexp^i
	|   rexp^i
lexp^i	->  (lexp^i | exp^{i+1}) qop^{({\rm{l}},i)} exp^{i+1}
lexp^6	->  @-@ exp^7
rexp^i	->  exp^{i+1} qop^{({\rm{r}},i)} (rexp^i | exp^{i+1})
exp^{10} ->  @\@ apat_1 ... apat_n @->@ exp	& (\tr{lambda abstraction}, n>=1)
	|   @let@ decls @in@ exp	        & ({\tr{let expression}})
	|   @if@ exp @then@ exp @else@ exp	& (\tr{conditional})
	|   @case@ exp @of@ @{@ alts  @}@	& (\tr{case expression})
	|   @do@ @{@ stmts @}@        	        & (\tr{do expression})
	|   fexp
fexp	->  [fexp] aexp				& (\tr{function application})

aexp 	->  qvar				& (\tr{variable})
	|   gcon				& (\tr{general constructor})
	|   literal				
	|   @(@ exp @)@			      & (\tr{parenthesized expression})
	|   @(@ exp_1 @,@ ... @,@ exp_k @)@	& (\tr{tuple}, k>=2)
	|   @[@ exp_1 @,@ ... @,@ exp_k @]@	& (\tr{list}, k>=1)
	|   @[@ exp_1 [@,@ exp_2] @..@ [exp_3] @]@ & (\tr{arithmetic sequence})
	|   @[@ exp @|@ qual_1 @,@ ... @,@ qual_n @]@	& (\tr{list comprehension}, n>=1)
	|   @(@ exp^{i+1} qop^{(a,i)} @)@        & (\tr{left section})
        |   @(@ qop^{(a,i)} exp^{i+1} @)@        & (\tr{right section})
        |   qcon @{@ fbind_1 @,@ ... @,@ fbind_n @}@ & (\tr{labeled construction}, n>=0)
Simon Peyton Jones's avatar
Simon Peyton Jones committed
63
        |   aexp_{\langle{}qcon\rangle{}} @{@ fbind_1 @,@ ... @,@ fbind_n @}@ & (\tr{labeled update}, n >= 1)
Simon Peyton Jones's avatar
Simon Peyton Jones committed
64
65
66
67
68
69
70
71
72

@@@
\indexsyn{exp}%
\index{exp@@"exp^i"}%
\index{lexp@@"lexp^i"}%
\index{rexp@@"rexp^i"}%
\indexsyn{aexp}%
\indexsyn{fexp}%

Simon Peyton Jones's avatar
Simon Peyton Jones committed
73
%	Removed Aug 2001: more misleading than helpful. SLPJ
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
% As an aid to understanding this grammar,
% Table~\ref{syntax-precedences} shows the relative precedence of
% expressions, patterns and definitions, plus an extended associativity.
% "-" indicates that the item is non-associative.
% 
% \begin{table}[tb]
% \[
% \centerline{
% \begin{tabular}{|l|c|}\hline
% Item						&	Associativity \\ 
% \hline
% 						&			\\
% simple terms, parenthesized terms               &	--	       	\\
% irrefutable patterns (@~@)                      &       --		\\
% as-patterns ({\tt @@})                          &       right		\\
% function application				&	left		\\
% @do@, @if@, @let@, lambda(@\@), @case@ (leftwards)&	right		\\
% @case@ (rightwards)				&	right		\\
% 						&			\\
% infix operators, prec. 9			&	as defined	\\
% \ldots						&	\ldots		\\
% infix operators, prec. 0			&	as defined	\\
% 						&			\\
% function types (@->@)				&	right		\\
% contexts (@=>@)					&	--		\\
% type constraints (@::@)				&	--		\\
% @do@, @if@, @let@, lambda(@\@) (rightwards)	&	right		\\
% sequences (@..@)				&	--		\\
% generators (@<-@)				&	--		\\
% grouping (@,@)					&	n-ary		\\
% guards (@|@)					&	--		\\
% case alternatives (@->@)			&	--		\\
% definitions (@=@)				&	--		\\
% separation (@;@)				&	n-ary		\\ 
% \hline
% \end{tabular}
% }
% \]
% %**<div align=center> <h4>Table 1</h4> </div>
% \ecaption{Precedence of expressions, patterns, definitions (highest to lowest)}
% \label{syntax-precedences}
% \end{table}
Simon Peyton Jones's avatar
Simon Peyton Jones committed
116
117
118

The grammar is ambiguous regarding the extent of lambda abstractions,
let expressions, and conditionals.  The ambiguity is resolved by the
Simon Peyton Jones's avatar
Simon    
Simon Peyton Jones committed
119
meta-rule that each of these constructs extends as far to the right as
Simon Peyton Jones's avatar
Simon Peyton Jones committed
120
121
possible.  As a consequence, each of these constructs has two precedences,
one to its left, which is the precedence used in the grammar; and
Simon Peyton Jones's avatar
Simon    
Simon Peyton Jones committed
122
one to its right, which is obtained via the meta-rule.  See the sample
Simon Peyton Jones's avatar
Simon Peyton Jones committed
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
parses below.

Expressions involving infix operators are disambiguated by the
operator's fixity (see Section~\ref{fixity}).  Consecutive
unparenthesized operators with the same precedence must both be either
left or right associative to avoid a syntax error.
Given an unparenthesized expression ``"x qop^{(a,i)} y qop^{(b,j)} z"'', parentheses
must be added around either ``"x qop^{(a,i)} y"'' or ``"y qop^{(b,j)}
z"'' when "i=j" unless "a=b={\rm l}" or "a=b={\rm r}".

Negation\index{negation} is the only prefix operator in
\Haskell{}; it has the same precedence as the infix @-@ operator
defined in the Prelude (see Figure~\ref{prelude-fixities}%
%*ignore
, page~\pageref{prelude-fixities}%
%*endignore
).

% 	I can't make head or tail of this para, so
%	I'm just deleting it.  SLPJ Dec 98
% The separation of function arrows from case alternatives solves
% the ambiguity that otherwise arises when an unparenthesized
% function type is used in an expression, such as the guard in a case
% expression.

Sample parses are shown below.
\[\bt{|l|l|}%%b
\hline
This                           	    & Parses as                             \\
\hline
@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@)               \\
\hline\et\]

For the sake of clarity, the rest of this section shows the syntax of
expressions without their precedences.

\subsection{Errors}
\label{basic-errors}\index{error}
Errors during expression evaluation, denoted by "\bot"\index{"\bot"},
167
are indistinguishable by a Haskell program from non-termination.  Since \Haskell{} is a
Simon Peyton Jones's avatar
Simon Peyton Jones committed
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
lazy language, all \Haskell{} types include "\bot".  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:
\bprog
@
error     :: String -> a
undefined :: a
@
\eprog
\indextt{error}
\indextt{undefined}
A 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.

\subsection{Variables, Constructors, Operators, and Literals}
%
@@@
aexp 	->  qvar				& (\tr{variable})
	|   gcon				& (\tr{general constructor})
	|   literal				
@@@
\indexsyn{var}%
\indexsyn{con}%
\indexsyn{varop}%
\indexsyn{conop}%
\indexsyn{op}%
@@@
gcon    ->  @()@
        |   @[]@
        |   @(,@\{@,@\}@)@
        |   qcon

var	->  varid | @(@ varsym @)@		& (\tr{variable})
qvar	->  qvarid | @(@ qvarsym @)@		& (\tr{qualified variable})
con	->  conid | @(@ consym @)@		& (\tr{constructor})
qcon	->  qconid | @(@ gconsym @)@		& (\tr{qualified constructor})
varop	->  varsym | \bkqB varid \bkqA		& (\tr{variable operator})
qvarop	->  qvarsym | \bkqB qvarid \bkqA	& (\tr{qualified variable operator})
conop	->  consym | \bkqB conid \bkqA		& (\tr{constructor operator})
qconop	->  gconsym | \bkqB qconid \bkqA	& (\tr{qualified constructor operator})
op	->  varop | conop 			& (\tr{operator})
qop     ->  qvarop | qconop			& (\tr{qualified operator})
gconsym ->  @:@ | qconsym
@@@
\indexsyn{gcon}%
\indexsyn{var}%
\indexsyn{qvar}%
\indexsyn{con}%
\indexsyn{qcon}%
\indexsyn{varop}%
\indexsyn{qvarop}%
\indexsyn{conop}%
\indexsyn{qconop}%
\indexsyn{qop}%
\indexsyn{gconsym}%

Simon Peyton Jones's avatar
Simon Peyton Jones committed
237
\Haskell{} provides special syntax to support infix notation.
Simon Peyton Jones's avatar
Simon    
Simon Peyton Jones committed
238
An {\em operator} is a function that can be applied using infix 
Simon Peyton Jones's avatar
Simon Peyton Jones committed
239
syntax (Section~\ref{operators}), or partially applied using a
Simon Peyton Jones's avatar
Simon    
Simon Peyton Jones committed
240
{\em section} (Section~\ref{sections}).
Simon Peyton Jones's avatar
Simon Peyton Jones committed
241

Simon Peyton Jones's avatar
Simon    
Simon Peyton Jones committed
242
An {\em operator} is either an {\em operator symbol}, such as @+@ or @$$@,
Simon Peyton Jones's avatar
Simon Peyton Jones committed
243
244
245
246
or is an ordinary identifier enclosed in grave accents (backquotes), such
as \bkqB@op@\bkqA.  For example, instead of writing the prefix application
@op x y@, one can write the infix application \mbox{@x@ \bkqB@op@\bkqA@ y@}.
If no fixity\index{fixity}
Simon Peyton Jones's avatar
Simon    
Simon Peyton Jones committed
247
declaration is given for \bkqB@op@\bkqA{} then it defaults
Simon Peyton Jones's avatar
Simon Peyton Jones committed
248
249
250
to highest precedence and left associativity
(see Section~\ref{fixity}).

Simon Peyton Jones's avatar
Simon Peyton Jones committed
251
252
253
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) 1 xs@.
Simon Peyton Jones's avatar
Simon Peyton Jones committed
254

Simon Peyton Jones's avatar
Simon Peyton Jones committed
255
256
257
258
259
260
261
262
263
264
265
%	This para is covered by Section 2.4 and 5.5.1
% A qualified name may only be used to refer to a variable or
% constructor imported from another module (see Section~\ref{import}), or
% defined at the top level, 
% but not in the definition of a new variable or constructor.  Thus
% \bprog
% let F.x = 1 in F.x   -- invalid
% \eprog
% incorrectly uses a qualifier in the definition of @x@, regardless of
% the module containing this definition.  Qualification does not affect
% the nature of an operator: @F.+@ is an infix operator just as @+@ is.
Simon Peyton Jones's avatar
Simon Peyton Jones committed
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303

Special syntax is used to name some constructors for some of the
built-in types, as found
in the production for "gcon" and "literal".  These are described
in Section~\ref{basic-types}.

\index{number!translation of literals}
An integer literal represents the
application of the function @fromInteger@\indextt{fromInteger} to the
appropriate value of type 
@Integer@.  Similarly, a floating point literal stands for an application of
@fromRational@\indextt{fromRational} to a value of type @Rational@ (that is, 
@Ratio Integer@).

\outline{
\paragraph*{Translation:}
The integer literal "i" is equivalent to @fromInteger@ "i",
where @fromInteger@ is a method in class @Num@ (see Section
\ref{numeric-literals}).\indexclass{Num}


The floating point literal "f" is equivalent to @fromRational@
("n" @Ratio.%@ "d"), where @fromRational@ is a method in class @Fractional@
and @Ratio.%@ constructs a rational from two integers, as defined in
the @Ratio@ library.\indexclass{Fractional}
The integers "n" and "d" are chosen so that "n/d = f".
}


\subsection{Curried Applications and Lambda Abstractions}
\label{applications}
\label{lambda-abstractions}
\index{lambda abstraction}
\index{application}
%\index{function application|see{application}}
%
@@@
fexp	->  [fexp] aexp				& (\tr{function application})
304
exp	->  @\@ apat_1 ... apat_n @->@ exp	& (\tr{lambda abstraction}, n>=1)
Simon Peyton Jones's avatar
Simon Peyton Jones committed
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
@@@
\indexsyn{exp}%
\indexsyn{fexp}%

\noindent
{\em Function application}\index{application} is written 
"e_1 e_2".  Application associates to the left, so the
parentheses may be omitted in @(f x) y@.  Because "e_1" could
be a data constructor, partial applications of data constructors are
allowed. 

{\em Lambda abstractions} are written 
"@\@ p_1 ... p_n @->@ e", where the "p_i" are {\em 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 {\em linear}\index{linearity}%
\index{linear pattern}---no variable may appear more than once in the set.

\outline{
\paragraph*{Translation:}
The following identity holds:
\begin{center}
\bt{lcl}%
\struthack{17pt}%
"@\@ p_1 ... p_n @->@ e"
	 & "=" &
	"@\@ x_1 ... x_n @-> case (@x_1@,@ ...@,@ x_n@) of (@p_1@,@ ...@,@ p_n@) ->@ e"
\et
\end{center}
where the "x_i" are new identifiers.
}
Given this translation combined with the semantics of case
expressions and pattern matching described in
Section~\ref{case-semantics}, if the
pattern fails to match, then the result is "\bot".

             
\subsection{Operator Applications}
\index{operator application}
Simon Peyton Jones's avatar
Simon Peyton Jones committed
345
%\index{operator application|hseealso{application}}
Simon Peyton Jones's avatar
Simon Peyton Jones committed
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
\label{operators}
%
@@@
exp	->  exp_1 qop exp_2
	|   @-@ exp				& (\tr{prefix negation})
qop     ->  qvarop | qconop			& (\tr{qualified operator})
@@@
\indexsyn{exp}%
\indexsyn{qop}%

\noindent
The form "e_1 qop e_2" is the infix application of binary
operator\index{operator} "qop" to expressions "e_1" and "e_2".  

The special
form "@-@e" denotes prefix negation\index{negation}, the only
prefix operator in \Haskell{}, and is 
syntax for "@negate @(e)".\indextt{negate}  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~\ref{prelude-fixities}%
%*ignore
, page~\pageref{prelude-fixities}%
%*endignore
).  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.

\outline{
\paragraph*{Translation:}
The following identities hold:
\begin{center}
\bt{lcl}%
\struthack{17pt}%
"e_1 op e_2" & "=" & "@(@op@)@ e_1 e_2" \\
"@-@e" & "=" & "@negate@ (e)"
\et
\end{center}
}

\subsection{Sections}
\index{section}
Simon Peyton Jones's avatar
Simon Peyton Jones committed
396
%\index{section|hseealso{operator application}}
Simon Peyton Jones's avatar
Simon Peyton Jones committed
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
\label{sections}
%
@@@
aexp	->  @(@ exp qop @)@ 
	|   @(@ qop exp @)@
@@@
\indexsyn{aexp}%

\noindent
{\em Sections} are written as "@(@ op e @)@" or "@(@ e op @)@", where
"op" is a binary operator and "e" is an expression.  Sections are a
convenient syntax for partial application of binary operators.

Syntactic precedence rules apply to sections as follows.
"@(@op~e@)@" is legal if and only if "@(x@~op~e@)@" parses 
in the same way as "@(x@~op~@(@e@))@";
and similarly for  "@(@e~op@)@".
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))@.

Because @-@ is treated specially in the grammar,
"@(-@ exp@)@" is not a section, but an application of prefix
negation,\index{negation} as
described in the preceding section.  However, there is a @subtract@
function defined in the Prelude such that
"@(subtract@ exp@)@" is equivalent to the disallowed section.
The expression "@(+ (-@ exp@))@" can serve the same purpose.

% Changed to allow postfix operators.  That is, in (op x), we no
Simon Peyton Jones's avatar
Simon    
Simon Peyton Jones committed
427
% longer add a \x -> which would require op to be binary instead
Simon Peyton Jones's avatar
Simon Peyton Jones committed
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
% of unary.

\outline{
\paragraph*{Translation:}
The following identities hold:
\begin{center}
\bt{lcl}%
\struthack{17pt}%
"@(@op e@)@" & "=" & "@\@ x @->@ x op e" \\
"@(@e op@)@" & "=" & "@\@ x @->@ e op x"
\et
\end{center}
where "op" is a binary operator, "e" is an expression, and "x" is a variable
that does not occur free in "e".
}

\subsection{Conditionals}
\label{conditionals}\index{conditional expression}
%
@@@
exp	->  @if@ exp_1 @then@ exp_2 @else@ exp_3
@@@
\indexsyn{exp}%

%\indextt{if ... then ... else ...}
A {\em conditional expression}
\index{conditional expression}
has the form 
"@if@ e_1 @then@ e_2 @else@ e_3" and returns the value of "e_2" if the
value of "e_1" is @True@, "e_3" if "e_1" is @False@, and "\bot"
otherwise.

\outline{
\paragraph*{Translation:}
The following identity holds:
\begin{center}
\bt{lcl}%
\struthack{17pt}%
"@if@ e_1 @then@ e_2 @else@ e_3"  & "=" & "@case@ e_1 @of { True ->@ e_2 @; False ->@ e_3 @}@"
\et
\end{center}
where @True@ and @False@ are the two nullary constructors from the 
type @Bool@, as defined in the Prelude.  The type of "e_1" must be @Bool@;
"e_2" and "e_3" must have the same type, which is also the type of the
entire conditional expression.
}

\subsection{Lists}
\label{lists}
%
@@@
exp     ->  exp_1 qop exp_2
aexp	->  @[@ exp_1 @,@ ... @,@ exp_k @]@	& (k>=1)
	|   gcon
gcon	-> @[]@
	| qcon
qcon	-> @(@ gconsym @)@
qop     -> qconop
qconop  -> gconsym
gconsym -> @:@
@@@
\indexsyn{aexp}%

{\em Lists}\index{list} are written "@[@e_1@,@ ...@,@ e_k@]@", where
"k>=1".  The list constructor is @:@, and the empty list is denoted @[]@.
Standard operations on
lists are given in the Prelude (see Section~\ref{basic-lists}, and
Appendix~\ref{stdprelude} notably Section~\ref{preludelist}).

\outline{
\paragraph*{Translation:}  
The following identity holds:
\begin{center}
\bt{lcl}%
\struthack{17pt}%
"@[@e_1@,@ ...@,@ e_k@]@"  & "=" & "e_1 @: (@e_2 @: (@ ... @(@e_k @: [])))@"
\et
\end{center}
where @:@ and @[]@ are constructors for lists, as defined in
the Prelude (see Section~\ref{basic-lists}).  The types
of "e_1" through "e_k" must all be the same (call it "t\/"), and the
type of the overall expression is @[@"t"@]@ (see Section~\ref{type-syntax}).
}
The constructor ``@:@'' is reserved solely for list construction; like
@[]@, it is considered part of the language syntax, and cannot be hidden or redefined.
Simon Peyton Jones's avatar
Simon Peyton Jones committed
513
It is a right-associative operator, with precedence level 5 (Section~\ref{fixity}).
Simon Peyton Jones's avatar
Simon Peyton Jones committed
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556

\subsection{Tuples}
\label{tuples}
%
@@@
aexp	->  @(@ exp_1 @,@ ... @,@ exp_k @)@	& (k>=2)
	| qcon
qcon -> @(,@\{@,@\}@)@

@@@
\indexsyn{aexp}%

{\em Tuples}\index{tuple} are written "@(@e_1@,@ ...@,@ e_k@)@", and may be
of arbitrary length "k>=2".  The constructor for an "n"-tuple is denoted by
@(,@\ldots@,)@, where there are "n-1" commas.  Thus @(a,b,c)@ and
@(,,) a b c@ denote the same value.
Standard operations on tuples are given
in the Prelude (see Section~\ref{basic-tuples} and Appendix~\ref{stdprelude}).

\outline{
\paragraph*{Translation:}  
"@(@e_1@,@ ...@,@ e_k@)@" for "k\geq2" is an instance of a "k"-tuple as
defined in the Prelude, and requires no translation.  If
"t_1" through "t_k" are the types of "e_1" through "e_k",
respectively, then the type of the resulting tuple is 
"@(@t_1@,@ ...@,@ t_k@)@" (see Section~\ref{type-syntax}).
}

\subsection{Unit Expressions and Parenthesized Expressions}
\label{unit-expression}
\index{unit expression}
%
@@@
aexp	->  gcon
        |   @(@ exp @)@
gcon	-> @()@
@@@
\indexsyn{aexp}%

\noindent
The form "@(@e@)@" is simply a {\em parenthesized expression}, and is
equivalent to "e".  The {\em unit expression} @()@ has type
@()@\index{trivial type} (see
557
558
559
Section~\ref{type-syntax}).  It is the only member of that type apart
from $\bot$, and can
be thought of as the ``nullary tuple'' (see Section~\ref{basic-trivial}).
Simon Peyton Jones's avatar
Simon Peyton Jones committed
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
\nopagebreak[4]

\outline{
\paragraph{Translation:}  
"@(@e@)@" is equivalent to "e".
}

\subsection{Arithmetic Sequences}
\label{arithmetic-sequences}
%
@@@
aexp	->  @[@ exp_1 [@,@ exp_2] @..@ [exp_3] @]@	
@@@
\indexsyn{aexp}%

\noindent


The {\em arithmetic sequence}\index{arithmetic sequence}
"@[@e_1@,@ e_2 @..@ e_3@]@" denotes a list of values of
type "t", where each of the "e_i" has type "t", and "t" is an
instance of class @Enum@.

\outline{
\paragraph{Translation:}
Arithmetic sequences satisfy these identities:
\begin{center}
\begin{tabular}{lcl}%
\struthack{17pt}%
@[ @"e_1"@.. ]@		& "=" 
                        & @enumFrom@ "e_1" \\
@[ @"e_1"@,@"e_2"@.. ]@	& "=" 
                        & @enumFromThen@ "e_1" "e_2" \\
@[ @"e_1"@..@"e_3"@ ]@	& "=" 
                        & @enumFromTo@ "e_1" "e_3" \\
@[ @"e_1"@,@"e_2"@..@"e_3"@ ]@ 
                        & "=" 
                        & @enumFromThenTo@ "e_1" "e_2" "e_3"
\end{tabular}
\end{center}
where @enumFrom@, @enumFromThen@, @enumFromTo@, and @enumFromThenTo@
are class methods in the class @Enum@ as defined in the Prelude
(see Figure~\ref{standard-classes}%
%*ignore
, page~\pageref{standard-classes}%
%*endignore
).
}

The semantics of arithmetic sequences therefore depends entirely
Simon Peyton Jones's avatar
Simon Peyton Jones committed
610
on the instance declaration for the type "t".  
Simon Peyton Jones's avatar
Simon Peyton Jones committed
611
See Section~\ref{enum-class} for more details of which @Prelude@
Simon Peyton Jones's avatar
Simon Peyton Jones committed
612
type are in @Enum@ and their semantics.
Simon Peyton Jones's avatar
Simon Peyton Jones committed
613
614
615
616
617
618
619
620


\subsection{List Comprehensions}
\index{list comprehension}
\index{let expression!in list comprehensions}
\label{list-comprehensions}
%
@@@
621
aexp	-> @[@ exp @|@ qual_1 @,@ ... @,@ qual_n @]@	& (\tr{list comprehension}, n>=1)
622
623
624
qual	-> pat @<-@ exp 	& (\tr{generator})
         | @let@ decls		& (\tr{local declaration})
         | exp 			& (\tr{guard})
Simon Peyton Jones's avatar
Simon Peyton Jones committed
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
@@@
\indexsyn{aexp}
\indexsyn{qual}

\noindent
A {\em list comprehension} has the form "@[@ e @|@ q_1@,@ ...@,@ q_n @]@,
n>=1," where the "q_i" qualifiers\index{qualifier} are either
\begin{itemize}
\item {\em generators}\index{generator} of the form "p @<-@ e", where
"p" is a 
pattern (see Section~\ref{pattern-matching}) of type "t" and "e" is an
expression of type "@[@t@]@"
\item {\em guards},\index{guard} which are arbitrary expressions of
type @Bool@ 
\item {\em local bindings} that provide new definitions for use in
the generated expression "e" or subsequent guards and generators.
\end{itemize}

Such a list comprehension returns the list of elements
produced by evaluating "e" 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~\ref{pattern-matching}), and if a
match fails then that element of the list is simply skipped over.  Thus:\nopagebreak[4]
\bprog
@
[ x |  xs   <- [ [(1,2),(3,4)], [(5,4),(3,2)] ], 
      (3,x) <- xs ]
@
\eprog
yields the list @[4,2]@.  If a qualifier is a 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:
\[\ba{lll}
@[ x | x <- x, x <- x ]@ & = & @[ z | y <- x, z <- y]@ \\
\ea\]
\outline{
\paragraph{Translation:}
List comprehensions satisfy these identities, which may be
used as a translation into the kernel:
\begin{center}
\bt{lcl}%
\struthack{17pt}%
Simon Peyton Jones's avatar
Simon Peyton Jones committed
669
670
"@[ @ e@ | True ]@" & = & "@[@e@]@" \\
"@[ @ e@ | @q@ ]@" & = & "@[@~ e~@|@~q@, True ]@" \\
Simon Peyton Jones's avatar
Simon Peyton Jones committed
671
672
673
674
675
"@[ @ e@ | @b@,@~ Q ~@]@" & = &
	"@if@~b~@then@~@[ @ e@ | @Q@ ]@~@else []@" \\
"@[ @ e@ | @p @<-@ l@,@~ Q@ ]@" & = &
	"@let ok@~p~@=@~@[ @ e@ | @Q@ ]@" \\
&&       @    ok _ = []@ \\
Simon Peyton Jones's avatar
Simon Peyton Jones committed
676
&&	"@in concatMap ok@~ l" \\
Simon Peyton Jones's avatar
Simon Peyton Jones committed
677
678
679
680
"@[ @ e@ | let@~decls@,@~ Q@ ]@" & = &
	"@let@~decls~@in@~@[ @ e@ | @Q@ ]@"
\et
\end{center}
681
682
683
684
685
where "e" ranges over expressions, "p" over
patterns, "l" over list-valued expressions, "b" over
boolean expressions, "decls" over declaration lists, 
"q" over qualifiers, and "Q" over sequences of qualifiers.  "@ok@" is a fresh variable.
The function @concatMap@, and boolean value @True@, are defined in the Prelude.
Simon Peyton Jones's avatar
Simon Peyton Jones committed
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
}

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
\ref{monomorphism}).

\subsection{Let Expressions}
\index{let expression}
\label{let-expressions}
%
% Including this syntax blurb does REALLY bad things to page breaking
% in the 1.[12] report (sigh); ToDo: hope it goes away.
@@@
exp	->  @let@ decls @in@ exp
@@@
\indexsyn{exp}
\index{declaration!within a {\tt let} expression}

\noindent
{\em Let expressions} have the general form
"@let {@ d_1 @;@ ...  @;@ d_n @} in@ e",
and introduce a
nested, lexically-scoped, 
mutually-recursive list of declarations (@let@ is often called @letrec@ in
other languages).  The scope of the declarations is the expression "e"
and the right hand side of the declarations.  Declarations are
described in Section~\ref{declarations}.  Pattern bindings are matched
lazily; an implicit @~@ makes these patterns
irrefutable.\index{irrefutable pattern}
For example, 
\bprog
@
let (x,y) = undefined in @"e"@
@
\eprog
does not cause an execution-time error until @x@ or @y@ is evaluated.

\outline{
\paragraph*{Translation:} The dynamic semantics of the expression 
"@let {@ d_1 @;@ ...  @;@ d_n @} in@ e_0" are captured by this
translation: After removing all type signatures, each
declaration "d_i" is translated into an equation of the form 
"p_i @=@ e_i", where "p_i" and "e_i" are patterns and expressions
respectively, using the translation in
Section~\ref{function-bindings}.  Once done, these identities
hold, which may be used as a translation into the kernel:
\begin{center}
\bt{lcl}%
\struthack{17pt}%
Simon Peyton Jones's avatar
Simon Peyton Jones committed
736
@let {@"p_1"@=@"e_1"@; @ ... @; @"p_n"@=@"e_n"@} in@ "e_0"
737
      &=& @let (~@"p_1"@,@ ... @,~@"p_n"@) = (@"e_1"@,@ ... @,@"e_n"@) in@ "e_0" \\
Simon Peyton Jones's avatar
Simon Peyton Jones committed
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
@let @"p"@ = @"e_1" @ in @ "e_0"
	&=& @case @"e_1"@ of ~@"p"@ -> @"e_0"	\\
	& & {\rm where no variable in "p" appears free in "e_1"} \\
@let @"p"@ = @"e_1" @ in @ "e_0"
      &=& @let @"p"@ = fix ( \ ~@"p"@ -> @"e_1"@) in@ "e_0"
\et
\end{center}
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.
%\folks{Needs work -- KH}
% This same semantics applies to the top-level of
%a program that has been translated into a @let@ expression,
% as described at the beginning of Section~\ref{modules}.
The static semantics of the bindings in a @let@ expression
are described in 
Section~\ref{pattern-bindings}.
}

\subsection{Case Expressions}
\label{case}
%
@@@
exp	->  @case@ exp @of@ @{@ alts @}@
alts	->  alt_1 @;@ ... @;@ alt_n 		& (n>=0)
alt	->  pat @->@ exp [@where@ decls]
	|   pat gdpat [@where@ decls]
	|					& (empty alternative)

gdpat   ->  gd @->@ exp [ gdpat ]
gd	->  @|@ exp^0 
@@@
\indexsyn{exp}%
\indexsyn{alts}%
\indexsyn{alt}%
\indexsyn{gdpat}%
\indexsyn{gd}%

A {\em case expression}\index{case expression} has the general form
\[
"@case@ e @of { @p_1 match_1 @;@ ... @;@ p_n  match_n @}@"
\]
where each "match_i" is of the general form
\[\ba{lll}
 & "@|@ g_{i1}"   & "@->@ e_{i1}" \\
 & "..." \\
 & "@|@ g_{im_i}" & "@->@ e_{im_i}" \\
 & \multicolumn{2}{l}{"@where@ decls_i"}
\ea\]
788
789
(Notice that in the syntax rule for "gd", the ``@|@'' is a 
terminal symbol, not the syntactic metasymbol for alternation.)
Simon Peyton Jones's avatar
Simon Peyton Jones committed
790
Each alternative "p_i match_i" consists of a 
791
792
793
794
pattern\index{pattern} "p_i" and its matches, "match_i".
Each match in turn
consists of a sequence of pairs of guards\index{guard}
"g_{ij}" and bodies "e_{ij}" (expressions), followed by
Simon Peyton Jones's avatar
Simon Peyton Jones committed
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
optional bindings ("decls_i") that scope over all of the guards and
expressions of the alternative.  An alternative of the form
\[
"pat @->@ exp @where@ decls"
\]
is treated as shorthand for:
\[\ba{lll}
 & "pat @| True@"   & "@->@ exp" \\
 & \multicolumn{2}{l}{"@where@ decls"}
\ea\]

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 "e"
Simon Peyton Jones's avatar
Simon Peyton Jones committed
811
812
813
814
815
816
817
818
819
820
821
822
against the individual alternatives.  The alternatives are tried
sequentially, from top to bottom.  If "e" matches the pattern in the
alternative, the guards for that alternative are tried sequentially
from top to bottom, in the environment of the case expression extended
by the bindings created during the matching of the pattern and by the
"decls_i" associated with that alternative.  If one of the guards
evaluates to @True@, the corresponding right-hand side is evaluated.
If all the guards evaluate to @False@, matching continues with the
next alternative.  If no match succeeds, the result is "\bot".
Pattern matching is described in Section~\ref{pattern-matching}, with
the formal semantics of case expressions in
Section~\ref{case-semantics}.
Simon Peyton Jones's avatar
Simon Peyton Jones committed
823
824
825
826
827
828
829
830
831

\subsection{Do Expressions}
\index{do expression}
\label{do-expressions}
\index{let expression!in do expressions}
\index{monad}
%
@@@
exp -> @do@ @{@ stmts @}@             & (\tr{do expression})
Simon Peyton Jones's avatar
Simon Peyton Jones committed
832
stmts -> stmt_1 ... stmt_n exp [@;@]  &  (n>=0)
833
834
835
stmt -> exp @;@
      | pat @<-@ exp @;@
      | @let@ decls @;@
Simon Peyton Jones's avatar
Simon    
Simon Peyton Jones committed
836
      | @;@			& (empty statement)
Simon Peyton Jones's avatar
Simon Peyton Jones committed
837
@@@
Simon Peyton Jones's avatar
Simon Peyton Jones committed
838
839
840
841
842
% The semicolons are done differently than for decls
%  Reason: to do it the same way would mean:
%	stmts -> stmt1 ; ... ; stmtn ; exp [;]
% Now, what happens if n=0?  Is there a ';' before the exp or not?
% Putting the ';' on the end of the stmt makes that clear.
Simon Peyton Jones's avatar
Simon Peyton Jones committed
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
\indexsyn{exp}%
\indexsyn{stmt}%
\indexsyn{stmts}%

A {\em do expression} provides a more conventional syntax for monadic programming.
It allows an expression such as 
\bprog
@
  putStr "x: "    >> 
  getLine         >>= \l ->
  return (words l)
@
\eprog
to be written in a more traditional way as:
\bprog
@
  do putStr "x: "
     l <- getLine
     return (words l)
@
\eprog
\outline{
\paragraph*{Translation:} 
Do expressions satisfy these identities, which may be
used as a translation into the kernel, after eliminating empty "stmts":
\begin{center}
\bt{lcl}%
\struthack{17pt}%
@do {@"e"@}@                       &=& "e"\\
@do {@"e"@;@"stmts"@}@             &=& "e" @>> do {@"stmts"@}@ \\
@do {@"p"@ <- @"e"@; @"stmts"@}@   &=& @let ok @"p"@ = do {@"stmts"@}@\\
                                   & & @    ok _ = fail "..."@\\
                                   & & @  in @"e"@ >>= ok@ \\
@do {let@ "decls"@; @"stmts"@}@  &=& @let@ "decls" @in do {@"stmts"@}@\\
\et
\end{center}
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\indexclass{Monad}; 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.

\subsection{Datatypes with Field Labels}
\label{field-ops}
\index{data declaration@@{\tt data} declaration}
\index{label}
\index{field label|see{label}}
A datatype declaration may optionally include field labels for some or
all of the components of the type (see Section~\ref{datatype-decls}).
Readers unfamiliar with datatype declarations in \Haskell{} may wish
to read Section \ref{datatype-decls} first.
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.
905
Within a datatype, however, a field label can be used in more
Simon Peyton Jones's avatar
Simon Peyton Jones committed
906
than one constructor provided the field has the same typing in all
907
constructors. To illustrate the last point, consider:
Simon Peyton Jones's avatar
Simon Peyton Jones committed
908
\bprog
909
910
911
912
@
  data S = S1 { x :: Int } | S2 { x :: Int }   -- OK
  data T = T1 { y :: Int } | T2 { y :: Bool }  -- BAD
@
Simon Peyton Jones's avatar
Simon Peyton Jones committed
913
\eprog
914
915
916
Here @S@ is legal but @T@ is not, because @y@ is given 
inconsistent typings in the latter.

Simon Peyton Jones's avatar
Simon Peyton Jones committed
917
918
919
920
921
922
\subsubsection{Field Selection}
@@@
aexp ->     qvar
@@@
\index{field label!selection}

923
924
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
Simon Peyton Jones's avatar
Simon Peyton Jones committed
925
926
927
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
928
929
affects selector functions; in record construction (Section~\ref{record-construction}) 
and update (Section~\ref{record-update}), field labels
Simon Peyton Jones's avatar
Simon Peyton Jones committed
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
cannot be confused with ordinary variables. 

\outline{
\paragraph*{Translation:} 
A field label "f" introduces a selector function defined as:
\begin{center}
\bt{lcl}
\struthack{17pt}%
"f"@ x@ &=&@case x of {@ "C_1 p_{11} \ldots p_{1k}" @ -> @ "e_1" @;@ 
 "\ldots" @;@ "C_n p_{n1} \ldots p_{nk}" @ -> @ "e_n" @}@\\
\et
\end{center}
where "C_1 \ldots C_n" are all the constructors of the datatype containing a
field labeled with "f", "p_{ij}" is @y@ when "f" labels the "j"th
component of "C_i" or @_@ otherwise, and "e_i" is @y@ when some field in
"C_i" has a label of "f" or @undefined@ otherwise.
}
\subsubsection{Construction Using Field Labels}
948
\label{record-construction}
Simon Peyton Jones's avatar
Simon Peyton Jones committed
949
950
951
952
953
954
955
956
957
958
959
960
\index{field label!construction}
@@@
aexp ->  qcon @{@ fbind_1 @,@ ... @,@ fbind_n @}@ & (\tr{labeled construction}, n>=0)
fbind   ->  qvar @=@ exp
@@@
\indexsyn{fbind}%

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.)
961
Construction using field labels is subject to the following constraints:
Simon Peyton Jones's avatar
Simon Peyton Jones committed
962
963
964
\begin{itemize}
\item Only field labels declared with the specified constructor may be
mentioned. 
965
\item A field label may not be mentioned more than once.
Simon Peyton Jones's avatar
Simon Peyton Jones committed
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
\item Fields not mentioned are initialized to $\bot$.
\item 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~\ref{strictness-flags}.
\end{itemize}

\outline{
\paragraph*{Translation:} 
In the binding "f" @=@ "v", the field "f" labels "v".
\begin{center}
\bt{lcl}
\struthack{17pt}%
"C" @{@ "bs" @}@ &=& "C (pick^C_1 bs @undefined@) \ldots (pick^C_k bs @undefined@)"\\
\et
\end{center}
where "k" is the arity of "C".

The auxiliary function "pick^C_i bs d" is defined as follows:
\begin{quote}
    If the "i"th component of a constructor "C" has the
986
    field label "f", and if "f=v" appears in the binding list
Simon Peyton Jones's avatar
Simon Peyton Jones committed
987
988
989
990
991
    "bs", then "pick^C_i bs d" is "v".  Otherwise, "pick^C_i bs d" is
    the default value "d".
\end{quote}
}
\subsubsection{Updates Using Field Labels}
992
\label{record-update}
Simon Peyton Jones's avatar
Simon Peyton Jones committed
993
994
995
996
997
\index{field label!update}
@@@
aexp ->  aexp_{\langle{}qcon\rangle{}} @{@ fbind_1 @,@ ... @,@ fbind_n @}@ & (\tr{labeled update}, n>=1)
@@@

998
Values belonging to a datatype with field labels may be
Simon Peyton Jones's avatar
Simon Peyton Jones committed
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
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:
\begin{itemize}
\item All labels must be taken from the same datatype.
\item At least one constructor must define all of the labels
mentioned in the update.
\item No label may be mentioned more than once.
\item An execution error occurs when the value being updated does
not contain all of the specified labels.
\end{itemize}
\outline{
\paragraph*{Translation:} 
Using the prior definition of "pick",
\begin{center}
\bt{lcl}
\struthack{17pt}%
"e" @{@ "bs" @}@ &=& @case@ "e" @of@\\
Simon Peyton Jones's avatar
Simon Peyton Jones committed
1017
&&@        @"C_1 v_1 ... v_{k_1}" @->@ "C_1 (pick^{C_1}_1 bs v_1) ... (pick^{C_1}_{k_1} bs v_{k_1})"\\
Simon Peyton Jones's avatar
Simon Peyton Jones committed
1018
&&@            @ ... \\
Simon Peyton Jones's avatar
Simon Peyton Jones committed
1019
&&@        @"C_j v_1 ... v_{k_j}" @->@ "C_j (pick^{C_j}_1 bs v_1) ... (pick^{C_j}_{k_j} bs v_{k_j})"\\
Simon Peyton Jones's avatar
Simon Peyton Jones committed
1020
1021
1022
1023
&&@        _ -> error "Update error"@\\
\et
\end{center}
where "\{C_1,...,C_j\}" is the set of constructors containing all labels
Simon Peyton Jones's avatar
Simon Peyton Jones committed
1024
in "bs", and "k_i" is the arity of "C_i".
Simon Peyton Jones's avatar
Simon Peyton Jones committed
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
}
Here are some examples using labeled fields:
\bprog
@
data T    = C1 {f1,f2 :: Int}
          | C2 {f1 :: Int,
                f3,f4 :: Char}
@
\eprog
\[\bt{|l|l|}%%b
\hline
Expression                       	    & Translation                       \\
\hline
@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@   \\
\hline\et\]
1043
The field @f1@ is common to both constructors in T.  This
Simon Peyton Jones's avatar
Simon Peyton Jones committed
1044
1045
1046
1047
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
1048
defines the set of field labels used in an update, such as
Simon Peyton Jones's avatar
Simon Peyton Jones committed
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
@x {f2 = 1, f3 = 'x'}@. 

\subsection{Expression Type-Signatures}
\index{expression type-signature}
\label{expression-type-sigs}
%
@@@
exp ->  exp @::@ [context @=>@] type
@@@
\indexsyn{exp}
\indextt{::}

\nopagebreak[4]
{\em Expression type-signatures} have the form "e @::@ t", where "e"
is an expression and "t" is a type (Section~\ref{type-syntax}); they
are used to type an expression explicitly
and may be used to resolve ambiguous typings due to overloading (see
Section~\ref{default-decls}).  The value of the expression is just that of
"exp".  As with normal type signatures (see
Section~\ref{type-signatures}), the declared type may be more specific than 
the principal type derivable from "exp", but it is an error to give
a type that is more general than, or not comparable to, the
principal type.
\outline{
\paragraph*{Translation:} 
\begin{center}
\bt{lcl}
\struthack{17pt}%
"e @::@ t" & = & "@let {@ v @::@ t@; @ v @=@ e @} in @v"
\et
\end{center}
}


\subsection{Pattern Matching}
\index{pattern-matching}
\label{pattern-matching}
\label{patterns}

{\em 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.
%it suffices to restrict the definition of the semantics of
%pattern-matching to case expressions.

\subsubsection{Patterns}
\label{pattern-definitions}

Patterns\index{pattern} have this syntax:
@@@
pat     ->  var @+@ integer            & (\tr{successor pattern})
	|   pat^0
pat^i	->  pat^{i+1} [qconop^{({\rm{n}},i)} pat^{i+1}]
	|   lpat^i
	|   rpat^i
lpat^i	->  (lpat^i | pat^{i+1}) qconop^{({\rm{l}},i)} pat^{i+1}
lpat^6	->  @-@ (integer | float)		& (\tr{negative literal})
rpat^i	->  pat^{i+1} qconop^{({\rm{r}},i)} (rpat^i | pat^{i+1})
Simon Peyton Jones's avatar
Simon Peyton Jones committed
1109
pat^{10} ->  apat
Simon Peyton Jones's avatar
Simon Peyton Jones committed
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
	|   gcon apat_1 ... apat_k		& (\tr{arity} gcon = k, k>=1)

apat	->  var [{\tt @@} apat]			& (\tr{as pattern})
	|   gcon				& (\tr{arity} gcon = 0) 
        |   qcon @{@ fpat_1 @,@ ... @,@ fpat_k @}@ & (\tr{labeled pattern}, k>=0)
	|   literal
	|   @_@					& (\tr{wildcard})
	|   @(@ pat @)@				& (\tr{parenthesized pattern})
	|   @(@ pat_1 @,@ ... @,@ pat_k @)@	& (\tr{tuple pattern}, k>=2)
	|   @[@ pat_1 @,@ ... @,@ pat_k @]@	& (\tr{list pattern}, k>=1) 
	|   @~@ apat				& (\tr{irrefutable pattern})

fpat    ->  qvar @=@ pat
@@@
\indexsyn{pat}%
\index{pat@@"pat^i"}%
\index{lpat@@"lpat^i"}%
\index{rpat@@"rpat^i"}%
\indexsyn{apat}%
\indexsyn{fpats}%
\indexsyn{fpat}%

The arity of a constructor must match the number of
sub-patterns associated with it; one cannot match against a
partially-applied constructor.

All patterns must be {\em linear}\index{linearity}
1137
1138
1139
1140
1141
\index{linear pattern}---no variable may appear more than once.  For
example, this definition is illegal:
@
  f (x,x) = x	-- ILLEGAL; x used twice in pattern
@
Simon Peyton Jones's avatar
Simon Peyton Jones committed
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198

Patterns of the form "var"{\tt @@}"pat" are called {\em as-patterns},
\index{as-pattern ({\tt {\char'100}})}
and allow one to use "var"
as a name for the value being matched by "pat".  For example,\nopagebreak[4]
\bprog
@
case e of { xs@@(x:rest) -> if x==0 then rest else xs }
@
\eprog
is equivalent to:
\bprog
@
let { xs = e } in
  case xs of { (x:rest) -> if x==0 then rest else xs }
@
\eprog

Patterns of the form @_@ are {\em
wildcards}\index{wildcard pattern ({\tt {\char'137}})} 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,
\bprog
@
case e of { [x,_,_]  ->  if x==0 then True else False }
@
\eprog
is equivalent to:
\bprog
@
case e of { [x,y,z]  ->  if x==0 then True else False }
@
\eprog
% where @y@ and @z@ are identifiers not used elsewhere.

%old:
%This translation is also 
%assumed prior to the semantics given below.

In the pattern matching rules given below we distinguish two kinds of
patterns: an {\em irrefutable pattern}
\index{irrefutable pattern}
is: a variable, a wildcard, "N apat" where "N" is a constructor
defined by @newtype@ and "apat" is irrefutable (see
Section~\ref{datatype-renaming}), 
\index{newtype declaration@@{\tt newtype} declaration} 
"var"{\tt @@}"apat" where "apat" is irrefutable,
or of the form "@~@apat" (whether or not "apat" is irrefutable).
All other patterns are {\em refutable}.
\index{refutable pattern}

\subsubsection{Informal Semantics of Pattern Matching}

Patterns are matched against values.  Attempting to match a pattern
can have one of three results: it may {\em fail\/}; it may {\em
succeed}, returning a binding for each variable in the pattern; or it
may {\em diverge} (i.e.~return "\bot").  Pattern matching proceeds
1199
from left to right, and outside to inside, according to the following rules:
Simon Peyton Jones's avatar
Simon Peyton Jones committed
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
\begin{enumerate}
\item Matching a value "v" against the irrefutable pattern
\index{irrefutable pattern}
"var" always succeeds and binds "var" to "v".  
Similarly, matching "v" against the irrefutable pattern "@~@apat" always succeeds.  
The free
variables in "apat" are bound to the appropriate values if matching
"v" against "apat" would otherwise succeed, and to "\bot" if matching
"v" against "apat" fails or diverges.  (Binding does {\em
not} imply evaluation.)

Matching any value against the wildcard pattern @_@ always succeeds
and no binding is done.

% Matching a value "con v" against the pattern "con apat" where "con" is an
% abstract datatype constructor and "apat" is irrefutable always succeeds
% and binds "var" to "v".  Matching "\bot" against the pattern "con apat" where
% "con" is an abstract datatype constructor and "apat" is irrefutable always
% succeeds and matches "\bot" to "apat".  

Operationally, this means that no matching is done on an
irrefutable pattern until one of the variables in the pattern 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.

\item
Matching a value "con v" against the pattern "con pat", where "con" is a
constructor defined by @newtype@, is equivalent to matching "v"
against the pattern "pat".   That is, constructors associated with
@newtype@ serve only to change the type of a value.\index{newtype declaration@@{\tt newtype} declaration}

\item Matching "\bot" against a refutable pattern always diverges.
\index{refutable pattern}

\item Matching a non-"\bot" value can occur against three kinds of
refutable patterns:
\begin{enumerate}
\item Matching a non-"\bot" value against a pattern whose outermost
component is a constructor defined by @data@ 
\index{constructed pattern}
fails if the value being matched was created by a 
different constructor.  If the constructors are
the same, the result of the match is the result of matching the
sub-patterns 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.  

%Also, literals (characters, positive and
%negative integers, and the unit value @()@) are treated as nullary
%constructors.
\item Numeric literals are matched using the overloaded @==@ function.  
The behavior of numeric patterns depends entirely on the definition of
@==@ and @fromInteger@ (integer literals) or @fromRational@ (floating point literals)
for the type of object being matched.

\item Matching a non-"\bot" value "x" against a pattern of the form
"n@+@k"
\index{n+k pattern@@"n@+@k" pattern}
(where "n" is a variable and "k" is a positive integer
literal) succeeds if "x>=k", resulting in the binding of "n" to "x-k",
and fails if "x<k".  The behavior of "n@+@k" patterns depends entirely
on the underlying definitions of @>=@, @fromInteger@, and @-@ for the
type of the object being matched.
\end{enumerate}

\item
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 @_@).

\item
The result of matching a value "v" against an as-pattern "var"{\tt @@}"apat" is
\index{as-pattern ({\tt {\char'100}})}
the result of matching "v" against "apat" augmented with the binding of
"var" to "v".  If the match of "v" against "apat" fails or diverges,
then so does the overall match.
\end{enumerate}

Aside from the obvious static type constraints (for
example, it is a static error to match a character against a
1284
boolean), the following static class constraints hold: an integer
Simon Peyton Jones's avatar
Simon Peyton Jones committed
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
literal pattern
\index{integer literal pattern}
can only be matched against a value in the class
@Num@ and a floating literal pattern
\index{floating literal pattern}
can only be matched against a value
in the class @Fractional@.
A "n@+@k" pattern
\index{n+k pattern@@"n@+@k" pattern}
can only be matched
against a value in the class @Integral@.

Many people feel that "n@+@k" patterns should not be used.  These
patterns may be removed or changed in future versions of \Haskell{}. 

Here are some examples:
\begin{enumerate}
\item If the pattern @['a','b']@ is matched against "@['x',@\bot@]@", then @'a'@
"fails" to match against @'x'@, and the result is a failed match.  But
if @['a','b']@ is matched against "@[@\bot@,'x']@", then attempting to match
@'a'@ against "\bot" causes the match to "diverge".

\item These examples demonstrate refutable vs.~irrefutable
matching:
\bprog
@
(\ ~(x,y) -> 0) @"\bot"@    @"\Rightarrow"@    0
(\  (x,y) -> 0) @"\bot"@    @"\Rightarrow"@    @"\bot"@
@
\eprog
\bprog
@
(\ ~[x] -> 0) []    @"\Rightarrow"@    0
(\ ~[x] -> x) []    @"\Rightarrow"@    @"\bot"@
@
\eprog
\bprog
@
(\ ~[x,~(a,b)] -> x) [(0,1),@"\bot"@]    @"\Rightarrow"@    (0,1)
(\ ~[x, (a,b)] -> x) [(0,1),@"\bot"@]    @"\Rightarrow"@    @"\bot"@
@
\eprog
\bprog
@
(\  (x:xs) -> x:x:xs) @"\bot"@   @"\Rightarrow"@   @"\bot"@
(\ ~(x:xs) -> x:x:xs) @"\bot"@   @"\Rightarrow"@   @"\bot"@:@"\bot"@:@"\bot"@
@
\eprogNoSkip
\end{enumerate}
\nopagebreak[4]
% \bprog
% @@
% (\ t -> let (x,y) = t in 0) @@"\bot"@@    @@"\Rightarrow"@@    0
% (\ (x,y) -> 0) @@"\bot"@@    @@"\Rightarrow"@@    @@"\bot"@@
% @@
% \eprog
% \bprog
% @@
% (\ l -> let [x] = l in 0) []    @@"\Rightarrow"@@    0
% (\ l -> let [x] = l in x) []    @@"\Rightarrow"@@    @@"\bot"@@
% @@
% \eprog
% \bprog
% @@
% (\ l -> let [x,t] = l; (a,b) = t in x) [(0,1),@@"\bot"@@]    @@"\Rightarrow"@@    (0,1)
% (\ l -> let [x, (a,b)] = l in x) [(0,1),@@"\bot"@@]    @@"\Rightarrow"@@    @@"\bot"@@
% @@
% \eprog
% \bprog
% @@
% (\  (x:xs) -> x:x:xs) @@"\bot"@@   @@"\Rightarrow"@@   @@"\bot"@@
% (\ l -> let (x:xs) = l in x:x:xs) @@"\bot"@@   @@"\Rightarrow"@@   @@"\bot"@@:@@"\bot"@@:@@"\bot"@@
% @@
% \eprogNoSkip
% \end{enumerate}
Additional examples illustrating some of the subtleties of pattern matching
may be found in Section~\ref{datatype-renaming}.

Top level patterns in case
expressions and the set of top level patterns in function or pattern
bindings may have zero or more associated {\em guards}\index{guard}.
A guard is 
a boolean expression that is evaluated only after all of the
arguments have been successfully matched, and it must be true for the
overall pattern match to succeed.  The environment of the guard is the same
as the right-hand-side of the case-expression
alternative, function definition, or pattern binding to which it is attached.

The guard semantics have an obvious influence on the
strictness characteristics of a function or case expression.  In
particular, an otherwise irrefutable pattern
\index{irrefutable pattern}
may be evaluated because of a guard.  For example, in
\bprog
@
Simon Peyton Jones's avatar
Simon Peyton Jones committed
1380
1381
f :: (Int,Int,Int) -> [Int] -> Int
f ~(x,y,z) [a] | (a == y) = 1
Simon Peyton Jones's avatar
Simon Peyton Jones committed
1382
1383
1384
1385
1386
1387
1388
1389
@
\eprog
% \bprog
% @@
% f t [a] | a==y = 1 
%           where (x,y,z) = t
% @@
% \eprog
Simon Peyton Jones's avatar
Simon Peyton Jones committed
1390
both @a@ and @y@ will be evaluated by @==@ in the guard.
Simon Peyton Jones's avatar
Simon Peyton Jones committed
1391

1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404

\subsubsection{Formal Semantics of Pattern Matching}
\label{case-semantics}

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 Figures~\ref{simple-case-expr-1}--\ref{simple-case-expr-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.
  
Simon Peyton Jones's avatar
Simon Peyton Jones committed
1405
1406
1407
1408
\begin{figure}[tb]
\outlinec{
\begin{tabular}{@@{}cl}
(a)&@case @$e$@ of { @$alts$@ } @$=$@ (\@$v$@ -> case @$v$@ of { @$alts$@ }) @"e"\\
1409
&{\rm where $v$ is a new variable}\\
Simon Peyton Jones's avatar
Simon Peyton Jones committed
1410
1411
1412
(b)&@case @$v$@ of { @$p_1\ \ match_1$@;  @$\ldots{}$@ ; @$p_n\ \ match_n$@ }@\\
   &$=$@  case @$v$@ of { @$p_1\ \ match_1$@ ;@\\
   &@                _  -> @$\ldots{}$@ case @$v$@ of {@\\
1413
   &@                           @$p_n\ \ match_n$\ @;@\\
Simon Peyton Jones's avatar
Simon Peyton Jones committed
1414
1415
1416
1417
1418
1419
   &@                           _  -> error "No match" }@$\ldots$@}@\\
   &@ @{\rm where each $match_i$ has the form:}\\
   &@  | @$g_{i,1}$  @ -> @$e_{i,1}$@ ; @$\ldots{}$@ ; | @$g_{i,m_i}$@ -> @$e_{i,m_i}$@ where { @$decls_i$@ }@\\[4pt]
%\\
(c)&@case @$v$@ of { @$p$@ | @$g_1$@ -> @$e_1$@ ; @$\ldots{}$\\
   &\hspace*{4pt}@             | @$g_n$@ -> @$e_n$@ where { @$decls$@ }@\\
1420
   &\hspace*{2pt}@            _     -> @$e'$@ }@\\
Simon Peyton Jones's avatar
Simon Peyton Jones committed
1421
   &$=$@ case @$e'$@ of@\\
1422
   &   @  {@$y$@ -> @     {\rm (where "y" is a new variable)}\\
Simon Peyton Jones's avatar
Simon Peyton Jones committed
1423
1424
 &@   case @$v$@ of {@\\
   &@         @$p$@ -> let { @$decls$@ } in@\\
1425
   &@                if @$g_1$@ then @$e_1$@ @$\ldots{}$@ else if @$g_n$@ then @$e_n$@ else @$y$ \ @;@\\
Simon Peyton Jones's avatar
Simon Peyton Jones committed
1426
1427
1428
1429
1430
1431
   &@         _ -> @$y$@ }}@\\[4pt]
%\\
(d)&@case @$v$@ of { ~@$p$@ -> @$e$@; _ -> @$e'$@ }@\\
&$=$@ (\@$x'_1$ $\ldots$ $x'_n$ @->@ $e_1$ @) (case @$v$@ of { @$p$@->@ 
$x_1$@ })@ $\ldots$ @(case @$v$@ of { @$p$@ -> @$x_n$@})@\\
&{\rm where $e_1$ = $e\,[x'_1/x_1, \ldots, x'_n/x_n]$}\\[2pt]
1432
&{\rm $x_1, \ldots, x_n$ are all the variables in $p\/$; $x'_1, \ldots, x'_n$ are new variables}\\[4pt]
Simon Peyton Jones's avatar
Simon Peyton Jones committed
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
%\\
(e)&@case @$v$@ of { @$x${\tt @@}$p$@ -> @$e$@; _ -> @$e'$@ }@\\
&$=$@  case @$v$@ of { @$p$@ -> ( \ @$x$@ -> @$e$@ ) @$v$@ ; _ -> @$e'$@ }@\\[4pt]
%\\
(f)&@case @$v$@ of { _ -> @$e$@; _ -> @$e'$@ } @$=$@ @$e$\\[4pt]
\end{tabular}
}
%**<div align=center> <h4>Figure 3</h4> </div>
\ecaption{Semantics of Case Expressions, Part 1}
\label{simple-case-expr-1}
\end{figure}

\begin{figure}[tb]
\outlinec{
\begin{tabular}{@@{}cl}
(g)&@case @$v$@ of { @$K\ p_1 \ldots p_n$@ -> @$e$@; _ -> @$e'$@ }@\\
&$=$@ case @$v$@ of {@\\
&@     @$K\ x_1 \ldots x_n$@ -> case @$x_1$@ of {@\\
&@                    @$p_1$@ -> @$\ldots$@ case @$x_n$@ of { @$p_n$@ -> @$e$@ ; _ -> @$e'$@ } @$\ldots$\\
&@                    _  -> @$e'$@ }@\\
&@     _ -> @$e'$@ }@\\[2pt]
&{\rm at least one of $p_1, \ldots, p_n$ is not a variable; $x_1, \ldots, x_n$ are new variables}\\[4pt]
%\\
Simon Peyton Jones's avatar
Simon Peyton Jones committed
1456
1457
(h)&@case @$v$@ of { @$k$@ -> @$e$@; _ -> @$e'$@ } @$=$@ if (@$v$@==@$k$@) then @$e$@ else @$e'$ \\
&{\rm where $k$ is a character, string, or numeric literal.} \\[4pt]
Simon Peyton Jones's avatar
Simon Peyton Jones committed
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
%\\
(i)&@case @$v$@ of { @$x$@ -> @$e$@; _ -> @$e'$@ } @$=$@ case @$v$@ of { @$x$@ -> @$e$@ }@\\[4pt]
%\\
(j)&@case @$v$@ of { @$x$@ -> @$e$@ } @$=$@ ( \ @$x$@ -> @$e$@ ) @$v$\\[4pt]
%\\
(k)&@case @$N$ $v$@ of { @$N$@ @$p$@ -> @$e$@; _ -> @$e'$@ }@\\
&$=$@ case @$v$@ of { @$p$@ -> @$e$@; _ -> @$e'$@ }@\\
&{\rm where $N$ is a @newtype@ constructor}\\[4pt]
(l)&@case @$\bot$@ of { @$N$@ @$p$@ -> @$e$@; _ -> @$e'$@ } @$=$@ case @$\bot$@ of { @$p$@ -> @$e$@ }@\\
&{\rm where $N$ is a @newtype@ constructor}\\[4pt]
(m)& @case @ $v$ @ of { @ $K$ @ {@ $f_1$ @ = @ $p_1$ @ , @ $f_2$ @ = @
$p_2$ @ , @ $\ldots$ @} -> @ $e$ @; _ -> @ $e'$ @ }@\\
&$=$ @ case @$e'$@ of {@\\
&@   @$y$@ ->@\\
&@    case @ $v$ @ of { @\\
&@     @ $K$ @ { @ $f_1$ @ = @ $p_1$ @ } ->@\\
&@            case @ $v$ @ of {@ $K$ @ {@ $f_2$ @ = @ $p_2$ @ , @
$\ldots$ @ } -> @ $e$ @; _ -> @ $y$ @ };@\\
&@            _ -> @ $y$ @ }}@\\
&{\rm where $f_1$, $f_2$, $\ldots$ are fields of constructor $K$; $y$
is a new variable}\\[4pt]
(n)&@case @ $v$ @ of { @ $K$ @ {@ $f$ @ = @ $p$ @} -> @ $e$ @; _ -> @
$e'$ @ }@ \\
&$=$@ case @ $v$ @ of {@\\
&   @    @ $K$ $p_1\ \ldots \  p_n$ @ -> @ $e$ @; _ -> @ $e'$ @ }@\\
&{\rm where $p_i$ is $p$ if $f$ labels the $i$th component of $K$,
@_@ otherwise}\\
(o)&@case @ $v$ @ of { @ $K$ @ {} -> @ $e$ @; _ -> @
$e'$ @ }@ \\
&$=$@ case @ $v$ @ of {@\\
&   @    @ $K$ @_@ $\ldots$ @_ -> @ $e$ @; _ -> @ $e'$ @ }@\\
(p)&@case (@$K'$@ @$e_1$@ @$\ldots$@ @$e_m$@) of { @$K$@ @$x_1$@ @$\ldots$@ @$x_n$@ -> @$e$@; _ -> @$e'$@ } @$=$@ @$e'$\\
&{\rm where $K$ and $K'$ are distinct @data@ constructors of arity $n$ and $m$, respectively}\\[4pt]
%\\
(q)&@case (@$K$@ @$e_1$@ @$\ldots$@ @$e_n$@) of { @$K$@ @$x_1$@ @$\ldots$@ @$x_n$@ -> @$e$@; _ -> @$e'$@ }@\\
&$=$@  case @$e_1$@ of { @$x'_1$@ -> @$\ldots$@  case @$e_n$@ of { @$x'_n$@ -> @$e[x'_1/x_1 \ldots x'_n/x_n]$@ }@$\ldots$@}@\\
1494
&{\rm where $K$ is a constructor of arity $n$; $x'_1 \ldots x'_n$ are new variables}\\[4pt]
Simon Peyton Jones's avatar
Simon Peyton Jones committed
1495
1496
1497
%(l)&@case (@$A$@ @$ e_1$@) of {@$A$@ @$ x_1$@ -> @$e$@; _ -> @$e'$@ }@\\
%&$=$@ case @$e1$@ of { @$x_1$@ -> @$e$@ }@\\
%&{\rm where $A$ is constructor defined by @newtype@}\\
1498
(r)&@case @$v$@ of { @$x$@+@$k$@ -> @$e$@; _ -> @$e'$@ }@\\
Simon Peyton Jones's avatar
Simon Peyton Jones committed
1499
1500
&$=$@ if @$v$@ >= @$k$@ then let {@$x'$@ = @$v$@-@$k$@} in @$e[x'/x]$@ else @$e'$\\
&{\rm where $k$ is a numeric literal, and $x'$ is a new variable}\\
Simon Peyton Jones's avatar
Simon Peyton Jones committed
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
\end{tabular}
}
%**<div align=center> <h4>Figure 4</h4> </div>
\ecaption{Semantics of Case Expressions, Part 2}
\label{simple-case-expr-2}
\end{figure}

In Figures~\ref{simple-case-expr-1}--\ref{simple-case-expr-2}:
"e", "e'" and "e_i" are expressions; 
"g" and "g_i" are boolean-valued expressions; 
"p" and "p_i" are patterns; 
"v", "x", and "x_i" are variables; 
"K" and "K'" are algebraic datatype (@data@) constructors (including
Simon Peyton Jones's avatar
Simon Peyton Jones committed
1514
tuple constructors);  and "N" is a @newtype@ constructor\index{newtype declaration@@{\tt newtype} declaration}.
Simon Peyton Jones's avatar
Simon Peyton Jones committed
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
% For clarity, several rules are expressed using
% @let@ (used only in a non-recursive way); their usual purpose is to
% prevent name capture
% (e.g., in rule~(c)).  The rules may be re-expressed entirely with
% @cases@ by applying this identity:
% \[
% "@let @x@ = @y@ in @e@ @ =@  case @y@ of { @x@ -> @e@ }@"
% \]

%Using all but the last two identities (rules~(n) and~(o)) in Figure~\ref{simple-case-expr-2}
%in a left-to-right manner yields a translation into a
%subset of general @case@ expressions called {\em simple case expressions}.%
%\index{simple case expression}
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 "g_{i,j}"
in the "match_i" forms.
Subsequent identities manipulate the resulting @case@ expression into simpler
and simpler forms.
%The semantics of simple @case@ expressions is 
%given by the last two identities ((n) and~(o)).

Rule~(h) in Figure~\ref{simple-case-expr-2} involves the
overloaded operator @==@; it is this rule that defines the
meaning of pattern matching against overloaded constants.
\index{pattern-matching!overloaded constant}

%% When used as a translation, the identities in
%% Figure~\ref{simple-case-expr} will generate a very inefficient
%% program.  This can be fixed by using further @case@ or @let@ 
%% expressions, but doing so 
%% would clutter the identities, which are intended only to convey the semantics.

These identities all preserve the static semantics.  Rules~(d),~(e), and~(j)
use a lambda rather than a @let@; this indicates that variables bound
by @case@ are monomorphically typed (Section~\ref{type-semantics}).
\index{monomorphic type variable}

%**~footer

% Local Variables: 
% mode: latex
% End: