-
Notifications
You must be signed in to change notification settings - Fork 0
/
expressions.tex
1700 lines (1441 loc) · 68.7 KB
/
expressions.tex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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
63
64
65
66
67
68
69
70
71
72
73
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
116
117
118
119
120
121
122
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
167
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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
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
304
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
345
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
396
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
427
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
513
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
557
558
559
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
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
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
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
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
736
737
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
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
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
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
%!TEX root = reference.tex
\chapter{Expressions}
\label{expressions}
An expression is a form that denotes a \emph{value}. Evaluation is the computational process of realizing the denoted value.
\begin{figure}[htbp]
\begin{eqnarray*}
\ntDef{Expression}&\arrow&\ntRef{Variable}\\
&\choice&\ntRef{ScalarLiteral}\\
&\choice&\ntRef{AlgebraicConstructor}\\
&\choice&\ntRef{ApplicativeExpression}\\
&\choice&\ntRef{ConditionalExpression}\\
&\choice&\ntRef{CaseExpression}\\
&\choice&\ntRef{Condition}\\
&\choice&\ntRef{LetExpression}\\
&\choice&\ntRef{ValueExpression}\\
&\choice&\ntRef{AnonymousFunction}\\
&\choice&\ntRef{MemoFunction}\\
&\choice&\ntRef{TypedExpression}\\
&\choice&\ntRef{QuotedExpression}
\end{eqnarray*}
\caption{Expression}
\label{expressionFig}
\end{figure}
\begin{aside}
This chapter does not cover all forms of expression. Other chapters that address particular forms of expression include Chapter~\vref{variables} (variables), Chapter~\vref{lists} (list expressions), Chapter~\vref{strings} (string expressions) and Chapter~\vref{actors} (actors).
\end{aside}
\section{Variables in Expressions}
\label{varExpression}
\index{variable}
A variable as an expression is simply an occurrence of the variable's identifier (see Figure~\vref{variableFig}).
\subsubsection{Type Safety}
The type associated with a variable expression is derived from the type recorded for the variable in the environment.
\begin{prooftree}
\AxiomC{\q{( v},T\sub{v}\ \q{)}$\in\ $E}
\UnaryInfC{\typeprd{E}{\q{v}}{T\sub{v}'}}
\end{prooftree}
where \q{T\sub{v}'} is derived from \q{T\sub{v}} by means of \emph{refreshing}. I.e., if \q{T\sub{v}} takes the form:
\begin{lstlisting}[mathescape=true]
for all t$\subi{}$ such that T
\end{lstlisting}
then \q{T\sub{v}'} is \q{T} with all occurrences of type variable \q{t\subi} replaced with new type variables.
\section{Scalar Literal Expressions}
\label{scalarExpression}
There are three forms of scalar literal expression: numeric literals, string literals and enumerated symbols.
\begin{figure}[htbp]
\begin{eqnarray*}
\ntDef{ScalarLiteral}&\arrow&\ntRef{Integer}\\
&\choice&\ntRef{Long}\\
&\choice&\ntRef{Float}\\
&\choice&\ntRef{Decimal}\\
&\choice&\ntRef{String}\\
&\choice&\ntRef{EnumeratedSymbol}
\end{eqnarray*}
\caption{Scalar Literals}
\label{scalarExpressionFig}
\end{figure}
\subsection{32-bit Integer Literals}
\label{integerType}
\index{type!integer@\q{integer}}
The \q{integer} type is used to denote integral values in the range -2147483648..2147483647. In addition to the `normal' integers, there is a special denoted value -- \q{nonInteger} -- that denotes an invalid integer.
Integers may be written in a variety of styles (see Section~\vref{numericLiteral}; the most common form is the simple \ntRef{Decimal} notation.
\begin{figure}[htbp]
\begin{eqnarray*}
\ntDef{Integer}&\arrow&\ntRef{IntegerLiteral}\\
&\choice&\ntRef{Hexadecimal}\\
&\choice&\ntRef{CharacterCode}
\end{eqnarray*}
\caption{Integer Literals}
\label{integerExpressionFig}
\end{figure}
\noindent
The \q{integer} type is a so-called boxed type. Underlying the \q{integer} type is the raw type that denotes numeric value itself.
\index{type!integer@\q{integer}!raw}
The \q{integer} type can be defined using:
\begin{lstlisting}
type integer is integer(integer_)
\end{lstlisting}
where \q{integer\_} type is the raw type used internally to denote the machine representation of a 32-bit integer.
\label{rawInteger}
\begin{aside}
A raw \q{integer\_} is written with a trailing underscore:
\begin{lstlisting}
34_
\end{lstlisting}
In general, for an integer literal:
\begin{lstlisting}
34
\end{lstlisting}
is equivalent to the expression:
\begin{lstlisting}
integer(34_)
\end{lstlisting}
\end{aside}
\subsubsection{Largest and Smallest \q{integer}s}
The \q{largeSmall} contract is implemented for \q{integer}s. This contract (see Section~\vref{largeSmall}) defines the largest and the smallest \q{integer}s; its implementation is equivalent to
\begin{lstlisting}
implementation largeSmall over integer is {
def largest is integer(0x7fffffff_);
def smallest is integer(0x80000000_);
}
\end{lstlisting}
\subsection{64 bit Integer Literals}
\label{longType}
\index{type!long@\q{long}}
The \q{long} type is used to denote integral values in the range $-2^{63} \mbox{ to } 2^{63}-1$\footnote{I.e., -9223372036854775808..{}9223372036854775807}.
\begin{figure}[htbp]
\begin{eqnarray*}
\ntDef{Long}&\arrow&\ntRef{Decimal}\,\q{L}\\
&\choice&\ntRef{Hexadecimal}\,\q{L}
\end{eqnarray*}
\caption{Long Literals}
\label{longExpressionFig}
\end{figure}
As with \q{integer}s, the \q{long} type is a boxed type; is is defined equivalently to:
\begin{lstlisting}
type long is long(long_)
\end{lstlisting}
The \q{long\_} type is a raw type used internally that denotes the machine representation of a 64-bit integer. Raw \q{long\_} literals may be written using the underscore suffix (after the long indicator):
\begin{lstlisting}
45l_
\end{lstlisting}
\begin{aside}
There is no automatic conversion between \q{integer} values and \q{long} values. The \ntRef{TypeCoercion} expression may be used to convert between them. If \q{X} is an \q{integer} variable, then
\begin{lstlisting}
X as long
\end{lstlisting}
may be used to convert its value to \q{long}.
\begin{aside}
Where converting from \q{integer} to \q{long} does not lose any precision, the same cannot be said for other conversions.
\end{aside}
\end{aside}
\subsubsection{Largest and Smallest \q{long}s}
The \q{largeSmall} contract is implemented for \q{long}s. This contract (see Section~\vref{largeSmall}) defines the largest and the smallest \q{long} integers; its implementation is equivalent to
\begin{lstlisting}
implementation largeSmall over long is {
def largest is long(0x7fffffffffffffffL_)
def smallest is long(0x8000000000000000L_)
}
\end{lstlisting}
\subsection{Floating Point Literals}
\label{floatType}
\index{type!float@\q{float}}
The \q{float} type is used to represent fractional values. Floating point numbers are represented as IEEE double precision -- i.e., 64 bit.
\begin{figure}[H]
\begin{eqnarray*}
\ntDef{Float}&\arrow&\ntRef{FloatingPoint}
\end{eqnarray*}
\caption{Floating Point Literals}
\label{floatExpressionFig}
\end{figure}
\subsubsection{Largest and Smallest \q{float}s}
The \q{largeSmall} contract is implemented for \q{float}ing point numbers. Its implementation is equivalent to
\begin{lstlisting}
implementation largeSmall over float is {
def largest is __bits_float(0x7fefffffffffffffL_)
def smallest is __bits_float(0x1L_)
}
\end{lstlisting}
where \q{\_\_bits\_float} is a special function that allows a 64 bit bit string to represent a floating point number (the bit string \emph{is} the bit representation of the floating point number).
\subsection{Decimal Number Literals}
\label{decimalype}
\index{type!decimal@\q{decimal}}
The \q{decimal} point type is used to denote arbitrary precision decimal fractional values.
\begin{figure}[htbp]
\begin{eqnarray*}
\ntDef{DecimalNumber}&\arrow&\ntRef{Decimal}
\end{eqnarray*}
\caption{Decimal Literals}
\label{decimalExpressionFig}
\end{figure}
The \q{decimal} type is defined equivalently to:
\begin{lstlisting}
type decimal is decimal(decimal_)
\end{lstlisting}
where \q{nonDecimal} is used to denote non-legal decimal values.
\begin{aside}
\q{decimal} numbers are based on a decimal representation. This means that \q{decimal} numbers can represent certain fractional values exactly which \q{float} numbers cannot.
However, \q{decimal} computation is often substantially more expensive than \q{float}ing point computation.
\end{aside}
\subsection{String Literals}
\label{stringType}
\index{type!string@\q{string}}
The \q{string} type is used to denote string values.
\begin{figure}[htbp]
\begin{eqnarray*}
\ntDef{String}&\arrow&\ntRef{StringLiteral}
\end{eqnarray*}
\caption{String Expression}\label{stringInterpolationFig}
\end{figure}
The \q{string} type is defined equivalently to:
\begin{lstlisting}
type string is string(string_)
\end{lstlisting}
The simplest form of \q{string} literal is a sequence of characters enclosed in double-quotes -- see Section~\vref{string}.
In addition, quoted strings may include \emph{interpolation} expressions -- which are embedded expressions whose values are interpolated into the actual string value.
\subsection{String Interpolation}
\label{StringInterpolation}
\index{string!interpolation}
String interpolation refers to the embedding of variables and expressions in string literals. The actual string value of an interpolated \q{string} literal requires the evaluation of those variables and expressions.
For example, given a variable \q{X} with the value 24, then:
\begin{lstlisting}
"this has the value of X: $X"
"$(X*X) people saw this"
\end{lstlisting}
would have values:
\begin{lstlisting}[mathescape=true]
"this has the value of X: 24" ${\rm and}$ "576 people saw this"
\end{lstlisting}
respectively.
There are two modes of string interpolation: the dollar form corresponds to \q{display}ing a value and the hash form corresponds to \emph{coercing} a value to a \q{string} value (see Section~\vref{typeCoercionExpression}). The former produces a string which is intended to be parseable as the original value. It is also the form that is universally supported by all non-programmatic types.
\begin{aside}
If a \q{string} interpolation expression itself contains a string, the various quoting mechanisms for strings apply to that string also. I.e., it is not necessary to `double-quote' strings within \q{string} interpolation expressions.
For example, the \q{string} expression in:
\begin{lstlisting}
logMsg(info,"The price of cheese is $(priceOf("cheese"))");
\end{lstlisting}
works as expected: the argument to the \q{priceOf} function is the string literal \q{"cheese"}. An even more nested example is:
\begin{lstlisting}
logMsg(info,"The price of $P is $(priceOf("SKU$P"))");
\end{lstlisting}
In this example, we have a \q{string} interpolation expression embedded within another \q{string} interpolation expression.
\end{aside}
An \ntRef{Interpolation} expression may be followed by a \ntRef{FormattingSpec}. If present, then this specification is used to guide how values are formatted.
For example, the value of
\begin{lstlisting}
"--\$(120345567):999,999,999,999;--"
\end{lstlisting}
is the string:
\begin{lstlisting}
"--120,345,567--"
\end{lstlisting}
Detailed formatting is controlled by the \q{format} contract -- see Section~\vref{formatContract} -- which in turn means that different types of expression will have type appropriate ways of specifying the formatting.
\subsubsection{Semantics of String Interpolation}
String variable interpolation expressions may refer to variables that are in scope at the location of the string literal itself.
The meaning of a string interpolation is slightly different for the two forms of interpolation. An expression of the form:
\begin{lstlisting}[escapechar=|]
"|\emph{prefix}|$(|\emph{Exp}|)|\emph{suffix}|"
\end{lstlisting}
is interpreted as:
\begin{lstlisting}[mathescape=true]
"$\emph{prefix}$"++display($\emph{Exp}$)++"$\emph{suffix}$"
\end{lstlisting}
whereas the expression:
\begin{lstlisting}[mathescape=true]
"$\emph{prefix}$\#($\emph{Exp}$)$\emph{suffix}$"
\end{lstlisting}
is interpreted as being equivalent to:
\begin{lstlisting}[mathescape=true]
"$\emph{prefix}$"++($\emph{Exp}$ as string)++"$\emph{suffix}$"
\end{lstlisting}
\begin{aside}
The difference between \q{display} and \q{as} becomes most obviously apparent with \q{string}s themselves. Assuming that the variable \q{L} is bound to the \q{string} \q{"hello"}, the value of
\begin{lstlisting}
"alpha#(L)beta"
\end{lstlisting}
is the string
\begin{lstlisting}
"alphahellobeta"
\end{lstlisting}
whereas the value of
\begin{lstlisting}
"alpha$(L)beta"
\end{lstlisting}
is
\begin{lstlisting}
"alpha\"hello\"beta"
\end{lstlisting}
But in general, there may be many differences between the two forms of displayed value.
\end{aside}
If a \ntRef{FormattingSpec} is present, then the translation takes that into account also. For example, the expression:
\begin{lstlisting}[escapechar=|]
"|\emph{prefix}|$(|\emph{Exp}|):|\emph{Format}|;|\emph{suffix}|"
\end{lstlisting}
is equivalent to the expression:
\begin{lstlisting}[mathescape=true]
"$\emph{prefix}$"++_format($\emph{Exp}$,$\emph{Format}$)++"$\emph{suffix}$"
\end{lstlisting}
where \q{\_format} is part of the \q{format} contract -- see Section~\vref{formatContract}.
\begin{aside}
Note that this translation is the same for either the \q{\$} or \q{\#} interpolation form.
\end{aside}
\subsection{Enumerated Symbols}
\label{enumeratedSymbol}
\index{expression!enumerated symbol}
\index{enumerated symbol}
Enumerated symbols are written using regular identifiers (see Figure~\vref{enumSymbolFig}). Such a symbol must first have been declared within a type definition statement -- see Section~\vref{enumSymbol} -- which also determines the type of the symbol.
For example, the \q{boolean} type definition has two \ntRef{EnumeratedSymbol}s in its definition: \q{true} and \q{false}. Thus
\begin{lstlisting}
true
\end{lstlisting}
is an expression consisting of an \ntRef{EnumeratedSymbol} from the definition:
\begin{lstlisting}
type boolean is true or false;
\end{lstlisting}
\section{Algebraic Constructor Expressions}
\label{algebraicConstructors}
The \ntRef{AlgebraicConstructor} expressions are those that refer to constructors that are defined in \ntRef{AlgebraicType} definitions -- \emph{or those that arise from standard type schemas such as tuples and anonymous records}.
There are two primary forms of \ntRef{AlgebraicConstructor}s: positional \ntRef{ConstructorLiteral} terms and \ntRef{RecordLiteral} terms.
Records allow their fields to be addressed individually.
\begin{figure}[htbp]
\begin{eqnarray*}
\ntDef{AlgebraicConstructor}&\arrow&\ntRef{EnumeratedSymbol}\\
&\choice&\ntRef{ConstructorLiteral}\\
&\choice&\ntRef{TupleLiteral}\\
&\choice&\ntRef{RecordLiteral}\\
&\choice&\ntRef{AnonymousRecord}\\
&\choice&\ntRef{RecordAccess}\\
&\choice&\ntRef{SequenceExpression}
\end{eqnarray*}
\caption{Algebraic Constructor Expressions}
\label{algebraicExpressionFig}
\end{figure}
\subsection{Enumerated Symbol}
\label{enumeratedSymbol}
\index{expression!enumerated symbol}
\index{enumerated symbol literal}
\ntRef{EnumeratedSymbol}s denote symbolic values. In particular, it refers to symbols that are introduced in an algebraic \ntRef{TypeDefinition}.
\begin{figure}[htbp]
\begin{eqnarray*}
\ntDef{EnumeratedSymbol}&\arrow&\ntRef{Identifier}
\end{eqnarray*}
\caption{Enumerated Symbol Expression}
\label{enumeratedSymbolFig}
\end{figure}
Enumerated symbols have no internal structure; they are often used to define enumerations or for sentinels. For example, the \ntRef{Boolean} standard type can be defined
\begin{lstlisting}
type boolean is false or true
\end{lstlisting}
and the standard cons-list type uses \q{nil} to mark the empty list:
\begin{lstlisting}
type cons of t is cons(t,cons of t) or nil
\end{lstlisting}
\subsection{Constructor Literals}
\label{positionalConstructor}
\index{expression!positional constructor}
\index{positional constructor literal}
\ntRef{ConstructorLiteral} expressions denote data constructor values. In particular, it refers to constructors that are introduced in an algebraic \ntRef{TypeDefinition}.
\begin{figure}[htbp]
\begin{eqnarray*}
\ntDef{ConstructorLiteral}&\arrow&\ntRef{Identifier}\q{(}\,\ntRef{Expression}\,\q{,}\ldots\q{,}\,\ntRef{Expression}\,\q{)}
\end{eqnarray*}
\caption{Constructor Literal Expression}
\label{positionalConstructorFig}
\end{figure}
This definition also determines the valid types of the arguments to the constructor. For example, the type definition:
\begin{lstlisting}
type address is noWhere or someWhere(string,integer,string)
\end{lstlisting}
defines \q{someWhere} as the identifier of a \ntRef{ConstructorLiteral} and any instance must have exactly three arguments: a \q{string}, an \q{integer} and a \q{string}.
\paragraph{Accessing Elements of a Constructor Literal}
\index{positional constructor literal!accessing elements}
The only way that elements of a \ntRef{ConstructorLiteral} can be \emph{accessed} is via a pattern match -- see Section~\vref{posConPattern}. For example, given the definition of \q{address} above, we can `unpack' its argument using a pattern such as in
\begin{lstlisting}
fun city(someWhere(City,_,_)) is City
\end{lstlisting}
\subsection{Tuples}
\label{TupleTerms}
\index{expressions!tuple}
\index{tuples}
\index{informal combinations of elements}
A tuple consists of a sequence of expressions separated by commas and enclosed in parentheses. In effect, a tuple is a \ntRef{ConstructorLiteral} where the \ntRef{Identifier} is omitted -- and is automatically generated.
\begin{figure}[htbp]
\begin{eqnarray*}
\ntDef{TupleLiteral}&\arrow&\q{()}\\
&\choice&\q{((}\,\ntRef{Expression}\,\q{))}\\
&\choice&\q{(}\,\ntRef{Expression}\,\sequence{,}\,\ntRef{Expression}\,\q{)}\plustwo
\end{eqnarray*}
\caption{Tuple Literal Expression}
\label{tupleLiteralFig}
\end{figure}
Tuples allow a straightforward of the `casual' grouping of values together without requiring a specific type definition of a data structure.
\begin{aside}
Unlike \ntRef{ConstructorLiteral}s, tuples \emph{cannot} be defined using a \ntRef{TypeDefinition}. Instead, the tuple types form a \emph{type schema}.
\begin{aside}
Not a single type, because each arity of anonymous tuple type denotes a different type. However, all tuples are related by their tuple-ness.
\end{aside}
\end{aside}
In that tuples can be used to group elements together, they are somewhat similar to arrays. However, unlike arrays, each element of a tuple may be of a different type, and also unlike arrays, tuple elements may not be accessed via an indexing operation: tuples can only be `unwrapped' by some form of pattern matching.
For example, if the \q{split} function splits a list into a front half and back half, it may be used in a statement of the form:
\begin{lstlisting}
def (F,B) is split(L)
\end{lstlisting}
which has the effect of unpacking the result of the \q{split} function call and binding the variables \q{F} and \q{B} to the front half and back half of the list \q{L}.
The tuple notation is unremarkable except for two cases: the single element tuple and the zero element tuple.
\subsubsection{Zero-ary Tuples}
\label{zeroTuple}
\index{tuple!zero-ary}
Zero-element tuples \emph{are} permitted. A zero-element tuple, which is written
\begin{lstlisting}
()
\end{lstlisting}
is essentially a symbol.
\subsubsection{Singleton Tuples}
\index{single element tuples}
\index{tuples!single element}
Some special handling is required to represent tuples of one element.
The principal issue is the potential ambiguity between a tuple with one element and a normal operator override expression.
For example,
\begin{lstlisting}
(a+b)*c
\end{lstlisting}
is such a case: the inner term \q{(a+b)} is not intended to denote a tuple but simply the sum of \q{a} and \q{b}.
A singleton tuple \emph{may} be written; by doubly parenthesizing it. An expression of the form:
\begin{lstlisting}
((34))
\end{lstlisting}
denotes a singleton tuple with the integer 34 in it.
\begin{aside}
Fortunately, singleton tuples are not often required in programs.
\end{aside}
\subsection{Record Literals}
\label{recordLiteral}
\index{expressions!record literal}
\index{record literal}
A record literal is a collection of values identified by name.
Like \ntRef{ConstructorLiteral}s, the \ntRef{RecordLiteral} must have been defined with a \ntRef{TypeDefinition} statement. This also constrains the types of the expressions associated with the fields.
\begin{figure}[H]
\begin{eqnarray*}
\ntDef{RecordLiteral}&\arrow&\ntRef{Record}\ \choice\,\ntRef{ThetaRecord}\\
\ntDef{Record}&\arrow&\ntRef{Expression}\q{\{}\,\ntRef{RecordElement}\sequence{;}\ntRef{RecordElement}\,\q{\}}\\
\ntDef{RecordElement}&\arrow&\ntRef{Identifier}\ \q{=}\ \ntRef{Expression}\\
&\choice&\ntRef{Identifier}\ \q{:=}\ \ntRef{Expression}\\
&\choice&\q{type}\ \ntRef{Identifier}\ \q{=}\ \ntRef{Type}
\end{eqnarray*}
\caption{Record Literal Expression}\label{recordLiteralFig}
\end{figure}
There are two variants of the \ntRef{RecordLiteral}: the \ntRef{Record} form and the \ntRef{ThetaRecord} form. This section focuses on the former.
For example, given the type definition:
\begin{lstlisting}
type employee is emp{
name has type string;
hireDate has type date;
salary has type ref integer;
dept has type ref string;
}
\end{lstlisting}
A literal \q{emp} value will look like:
\begin{lstlisting}
def E is emp{
name = "Fred Nice";
hireDate = today();
salary := 23000;
dept := "mail"
}
\end{lstlisting}
\begin{aside}
Fields whose type is a \q{ref}erence type -- see Section~\vref{referenceType} -- are defined within the record using the \q{:=} operator. All other fields are defined using the \q{=} operator.
\end{aside}
For any given \ntRef{RecordLiteral} \emph{all} the fields of the record must be associated with a value. This value is either explicitly given or can be supplied by a \q{default} declaration within the type definition itself.
Fields within a \ntRef{RecordLiteral} are identified by name; and may be written in any order.
\subsection{Anonymous Records}
\label{anonRecord}
\index{expression!anonymous records}
\index{anonymous records}
An anonymous record is one which does not have an explicit label.
\begin{figure}[htbp]
\begin{eqnarray*}
\ntDef{AnonymousRecord}&\arrow&\q{\{}\,\ntRef{RecordElement}\,\q{;}\ldots\q{;}\,\ntRef{RecordElement}\,\q{\}}\\
&\choice&\q{\{}\,\ntRef{Definition}\sequence{;}\ntRef{Definition}\,\q{\}}
\end{eqnarray*}
\caption{Anonymous Record Literal Expression}\label{anonRecordLiteralFig}
\end{figure}
For example, an anonymous record consisting of a \q{name} and an \q{address} may be written:
\begin{lstlisting}
{name="Fred; address="1 Main St"}
\end{lstlisting}
Anonymous records have, as their type, a \ntRef{RecordType} (see Section~\vref{recordType}). The type of this record would be represented by:
\begin{lstlisting}
{ name has type string; address has type string}
\end{lstlisting}
\subsection{Accessing Fields of a Record}
\label{dotAccess}
\index{record literal!accessing}
\index{expressions!accessing record fields}
Record access expressions access the value associated with a field of a record value. The result may either be the field value, or a new record with a replaced field value.
\begin{figure}[htbp]
\begin{eqnarray*}
\ntDef{RecordAccess}&\arrow&\ntRef{Expression}\ \q{.}\ \ntRef{Identifier}
\end{eqnarray*}
\caption{Record Access Expression}\label{recordAccessFig}
\end{figure}
An expression of the form
\begin{lstlisting}
A.F
\end{lstlisting}
where \q{F} is the name of an attribute of the record \q{A} denotes the value of that attribute. For example, given the type definition
\begin{lstlisting}
type person is someone{
name has type string;
age has type integer;
}
\end{lstlisting}
and a \q{person} value bound to \q{P}:
\begin{lstlisting}
def P is someone{ name="fred"; age=32 }
\end{lstlisting}
then the expression \q{P.name} has value \q{"fred"}.
The (\q{.}) access operator is also used in cases where an anonymous record is used; for example given the record:
\begin{lstlisting}
def R is { alpha = "a"; beta=4}
\end{lstlisting}
then \q{R.alpha} has value \q{"a"}
\begin{aside}
The binding of the record access operator (\q{.}) is very strong. Thus, expressions such as
\q{A.L[ix]} and \q{A.F(a,b*3)}
are equivalent to
\begin{lstlisting}[mathescape=true]
(A.L)[ix] ${\rm and}$ (A.F)(a,b*3)
\end{lstlisting}
respectively.
\end{aside}
\subsubsection{Type Safety}
The type safety of a record access expression is couched in terms of \ntRef{AttributeConstraint}s: i.e., a record access expression implies that a value satisfies the appropriate \ntRef{AttributeConstraint}.
\begin{prooftree}
\AxiomC{\typeprd{E}{R}{T\ \q{where}\ T\ \q{implements}\ \q{\{\,F has type }T\sub{f}\q{\}}}}
\UnaryInfC{\typeprd{E}{R.F}{T\sub{f}}}
\end{prooftree}
\begin{aside}
This formulation of the type safety of record access expressions allows for some quite powerful usages. For example, the function:
\begin{lstlisting}
fun getName(R) is R.name
\end{lstlisting}
has type:
\begin{lstlisting}
getName has type for all r,f such that
(r)=>f where r implements {name has type f}
\end{lstlisting}
In effect, we can define programs that depend on particular attributes without having to be concrete about the actual types of the records being accessed.
\end{aside}
\subsection{Theta Records}
\label{thetaRecords}
\index{record literal!theta}
\index{theta record}
A \ntRef{ThetaRecord} is a record whose contents is specified by means of a \ntRef{ThetaEnvironment}. There are variants corresponding to labeled and anonymous records.
\begin{figure}[htbp]
\begin{eqnarray*}
\ntDef{ThetaRecord}&\arrow&[\ntRef{Expression}]\q{\{}\,\ntRef{Definition}\sequence{;}\ntRef{Definition}\,\q{\}}
\end{eqnarray*}
\caption{Theta Record Literal Expression}\label{thetaRecordLiteralFig}
\end{figure}
Externally, a \ntRef{ThetaRecord} is the same as a regular \ntRef{Record}; internally, however, its fields are defined very differently using \ntRef{Definition}s rather than attribute assignments.
If the record is labeled, then, as with all labeled records, the definitions within the \ntRef{ThetaEnvironment} must correspond exactly to the type definition.
\ntRef{ThetaRecord}s are especially convenient when the fields of the record are program values. For example, assuming a type definition such as:
\begin{lstlisting}
type onewayQ of t is onewayQ{
add has type (t)=>();
take has type ()=>t;
}
\end{lstlisting}
the literal:
\begin{lstlisting}
onewayQ{
private var Q := list of [];
prc add(X) do {
Q := list of [Q..,X]
}
fun take() is valof{
def H is head(Q);
Q := tail(Q);
valis H
}
}
\end{lstlisting}
defines a \q{onewayQ} record with two exposed program values -- \q{add} and \q{take}.
\begin{aside}
If there are `extra' definitions, they should be marked \q{private} which will exclude them from the record's type signature.
\end{aside}
\begin{aside}
A \ntRef{ThetaRecord} has many of the characteristics of an object in OO languages -- except that there is no concept of inheritance; nor is there a direct equivalence of the \q{self} or \q{this} keyword.
\end{aside}
\subsubsection{\q{private} fields}
\label{privateField}
\index{private fields@\q{private} fields}
\index{fields!private@\q{private}}
A definition within a \ntRef{ThetaRecord} that is marked \q{private} does \emph{not} `contribute' to the external type of the record; and neither can such an attribute be accessed via the \ntRef{RecordAccess} expression.
\subsection{Record Substitution Expression}
\label{recordOverride}
\index{replacing values in a record}
\index{expressions!substitute@\q{substitute}}
\index{record values!replacing fields}
An expression of the form:
\begin{lstlisting}[mathescape=true]
A substitute {att$\sub1$=$\ntRef{Expression}\sub1\sequence{;}$att$\subn$=$\ntRef{Expression}\subn$}
\end{lstlisting}
denotes the value obtained by replacing the attributes \q{att}\subi{} in \q{A} with the expressions \ntRef{Expression}\subi.
\begin{figure}[htbp]
\begin{eqnarray*}
\emph{Expression}&\arrowplus&\ntRef{Expression}\ \q{substitute}\ \ntRef{AnonymousRecord}
\end{eqnarray*}
\caption{Record Override Expression}\label{recordOverrideFig}
\end{figure}
For example, the expression
\begin{lstlisting}
P substitute {age=33}
\end{lstlisting}
has value
\begin{lstlisting}
someone{name="fred"; age=33}
\end{lstlisting}
\begin{aside}
This expression has a separate value to that of \q{P} itself; evaluating the \q{substitute} does not side-effect \q{P}.
\end{aside}
\noindent
The semantics of \q{substitute} is based on the notion of a `shallow copy'. The value of the expression:
\begin{lstlisting}
P substitute { age=33 }
\end{lstlisting}
is a new term whose fields consist of all the fields of \q{P} -- with the exception of the \q{age} field. The \q{substitute} expression does not imply a `deep' or complete copy of its left hand side.
\begin{aside}
\index{expressions!substitute@\q{substitute}!ref fields@\q{ref} fields}
\index{record values!replacing ref fields@replacing \q{ref} fields}
\index{ref field@\q{ref} field}
This only has significance if the record contains any \q{ref} fields. In particular, the resulting expression \emph{contains} the same \q{ref} fields as the original; and a subsequent assignment to a \q{ref} field will affect both the original and the substituted term.
For example, given this type definition:
\begin{lstlisting}
type account is account{
name has type string;
balance has type ref float;
}
\end{lstlisting}
and given the variable bindings:
\begin{lstlisting}
def A is account{ name = "fred"; balance := 0.0 };
def B is A substitute { name = "peter" }
\end{lstlisting}
then \q{A} and \q{B} both share the \emph{same} \q{ref} field. An assignment to one:
\begin{lstlisting}
A.balance := 5.9
\end{lstlisting}
is an assignment to the other. In this case, the value of \q{B.balance} is also \q{5.9}
\end{aside}
\begin{aside}
Note that if the \emph{right hand side} of a \q{substitute} contains a \q{ref} field, then the result will have the \q{ref} field from the right hand side, not the original.
For example, if we have:
\begin{lstlisting}
def C is A substitute { balance := 4.5 }
\end{lstlisting}
then \q{C} \emph{does not} share a \q{ref} with \q{A} and updating either will not affect the other.
\end{aside}
\subsubsection{Type Safety}
The type safety of an attribute substitute expression is couched in terms of \ntRef{AttributeConstraint}s.
\begin{prooftree}
\AxiomC{\typeprd{E}{R}{T\sub{R}\ \q{where}\ T\sub{R}\ \q{implements}\ T\sub{S}}}
\AxiomC{\typeprd{E}{S}{S\sub{S}\ \q{where}\ S\sub{S}\ \q{implements}\ T\sub{S}}}
\BinaryInfC{\typeprd{E}{R\ \q{substitute}\ S}{T\sub{R}}}
\end{prooftree}
The implication is that the `substitution' record \q{S} only contains attributes that are also present in the `substitute' expression \q{R}.
\section{Optional Expressions}
\label{optionExpression}
\index{option expression@\q{option} expression}
An \q{option} expression is used to handle cases where a value is not always guaranteed. The \q{option} type is built-in but is defined as though by the algebraic type definition in Program~\vref{optionTypeProg}.
\begin{program}
\begin{lstlisting}
type option of t is none or some(t)
\end{lstlisting}
\caption{The \q{option} Type}
\label{optionTypeProg}
\end{program}
The \q{option} type is intended to convey one of two possibilities: a given value exists -- in which case the \q{some} constructor is used -- or no value exists -- in which case \q{none} is used.
For example,
\begin{lstlisting}
some("alpha")
\end{lstlisting}
signals the definite \q{string} value \q{"alpha"}; whereas
\begin{lstlisting}
none
\end{lstlisting}
signals that there is no value.
The \q{option} type can be used as the return type of functions that must reliably signal whether or not a value exists.
\begin{aside}
The \q{option} type serves as a normal `replacement' for \q{null} that one sees in languages like Java.
\end{aside}
In addition to the \q{someValue} and \q{?.} operators -- described below in Section~\vref{someValue} and Section~\vref{optionChaining} -- two conditions are defined specifically for \q{option} expressions: \q{present} (see Section~\vref{presentCond}) and \q{has value} (see Section~\vref{hasValueCond}).
\subsection{Unwrap Option Value -- \q{someValue}}
\label{someValue}
\index{unwrap option value}
The \q{someValue} unwraps a \q{some} value and returns its contents. It is defined by the equation:
\begin{lstlisting}
fun someValue(some(X)) is X
\end{lstlisting}
\begin{aside}
\begin{aside}
The \q{someValue} function is partial. It is not defined in the case that its argument is not a \q{some} value. If \q{someValue} is invoked with q{none} then the program will terminate.
For this reason, the programmer should consider whether the \q{has value} condition (see Section~\vref{hasValueCond}) is a better fit.
\end{aside}
\end{aside}
\subsection{Option Field Access -- \q{?.}}
\label{optionChaining}
\index{?. operator@\q{?.} operator}
\index{accessing an optional value}
\index{option chaining}
The \q{?.} operator can be used similarly to a normal record field access (see \vref{dotAccess}) except that it takes an \q{option}al argument and returns an \q{option} value.
\begin{figure}[htbp]
\begin{eqnarray*}
\ntRef{RecordAccess}&\arrowplus&\ntRef{Expression}\ \q{?.}\ \ntRef{Identifier}
\end{eqnarray*}
\caption{Optional Record Access Expression}\label{optionAccessFig}
\end{figure}
The form of a optional field access is also similar to the field access; an expression of the form:
\begin{lstlisting}
A?.F
\end{lstlisting}
will access the \q{F} field from the wrapped record value in \q{A}. The result type of a option field access is also an \q{option}al.
For example, suppose that \q{R} has the type given by
\begin{lstlisting}
R has type option of Person
\end{lstlisting}
Its type can be approximated by (the difference is that field labels are not themselves functions):
\begin{lstlisting}
(?.) has type for all r,s such that
(option of r,(r=>s))=>option of s
\end{lstlisting}
I.e., it has a similar type to the \q{map} function (see \vref{mapFunction}) in the \q{mappable} contract.
However, it is actually best understood as a macro form. The macro definition of \q{?.} can be given in a single line macro:
\begin{lstlisting}
#?R ?. ?F ==> map((RR)=>RR.F,R)
\end{lstlisting}
where \q{map} is the implementation of the \q{mappable} contract for the \q{option} type.
\subsection{Default Option Expression -- \q{or else}}
\label{optionDefltChain}
\index{or else operator@\q{or else} operator}
\index{accessing an optional value with default}
\index{option chaining}
The \q{or else} operator can be used to unwrap an \q{option}al value -- giving a default in the case that it is actually \q{none}
\begin{figure}[htbp]
\begin{eqnarray*}
\ntRef{Expression}&\arrowplus&\ntRef{Expression}\ \q{or else}\ \ntRef{Expression}
\end{eqnarray*}
\caption{Optional Chaining with Default}\label{optionIndexAccessFig}
\end{figure}
The form of a optional access is:
\begin{lstlisting}
O or else D
\end{lstlisting}
where \q{O} has type \q{option of t} and \q{D} has type \q{t}. If \q{O} has value \q{some(X)} then the value is \q{X}, otherwise it is \q{D}.
Like \q{?.}, \q{or else} can be best understood as a macro:
\begin{lstlisting}
# ?O or else ?D ==> _optionDeflt(O,()=>D)
fun _optionDeflt(some(X),_) is X
| _optionDeflt(none,D) is D()
\end{lstlisting}
Notice that the default expression is not evaluated unless the value of \q{O} is \q{none}.
The \q{or else} operator is right associative. This means that they can be chained together if more than one default is possible:
\begin{lstlisting}
A or else B or else C
\end{lstlisting}
\section{Collection and Sequence Expressions}
\label{sequenceExpression}
\index{sequence!expressions}
\index{expressions!sequence}
\index{of@\q{of}!expression}
Collection expressions and sequence expressions are a syntactic feature that make it straightforward to represent collective values. The difference between a \q{collection} and a \q{sequence} is that the latter embodies a sequential ordering of the elements. A \q{collection} may have an ordering present; but that is not required by the contract and is not enforced in the notation.
A sequence expression represents a use of the standard \q{sequence} contract (see Program~\vref{sequenceContractDef}) to construct sequences of values.
\begin{aside}
There is a similar form to \ntRef{SequenceExpression} which is used to denote \emph{queries} -- the programmer's analog of set abstractions. \ntRef{Query} expressions are defined in Chapter~\ref{queries}.
\end{aside}
\begin{figure}[htbp]
\begin{eqnarray*}
\emph{Expression}&\arrowplus&\ntRef{SequenceExp}\\
\ntDef{SequenceExp}&\arrow&\ntRef{SequenceType}\ \q{of}\,\q{[}\ntRef{ExpSequence}\q{]}\\
&\choice&\q{[}\ntRef{ExpSequence}\q{]}\\
\ntDef{ExpSequence}&\arrow&[\ntRef{Expression}\q{..,}\,]\ntRef{Expression}\sequence{,}\ntRef{Expression}[\q{,..}\,\ntRef{Expression}]\\
\ntDef{SequenceType}&\arrow&\ntRef{Identifier}
\end{eqnarray*}
\caption{Sequence Expression}
\label{sequenceExpressionFig}
\end{figure}
I.e., a sequence expression consists of a sequence of \ntRef{Expression}s separated by commas. In addition, either -- but not both -- the tail or the front of the sequence may be denoted by an expression. Otherwise the sequence is nil-terminated.
An expression of the form:
\begin{lstlisting}[escapechar=|]
|\emph{Label}| of [|\emph{E\sub1}\sequence{,}\emph{E\subn}|]
\end{lstlisting}
is equivalent to the expression:
\begin{lstlisting}[escapechar=|]
_cons(|\emph{E\sub1}\sequence{,}|_cons(|\emph{E\subn}|,_nil())|\sequence{}|) has type |\emph{Label}| of %t|\sub{new}|
\end{lstlisting}
\emph{provided that \emph{Label} is the label of a \ntRef{Type} that implements the \q{sequence} contract} -- see Section~\vref{sequenceContract} and where \q{\%t\sub{new}} is a new type variable not occurring elsewhere. Included in that contract are two functions -- denoting the empty sequence (\q{\_nil()}) and a non-empty sequence (\q{\_cons()}) -- that are used to build the true value of a sequence expression.
A sequence can be built up from other sequences by prepending to them. An expression of the form:
\begin{lstlisting}[escapechar=|]
|\emph{Label}| of [|\emph{E\sub1}\sequence{,}\emph{E\sub{n-1}}\q{,..}\emph{E\subn}|]
\end{lstlisting}
is equivalent to the expression:
\begin{lstlisting}[escapechar=|]
_cons(|\emph{E\sub1}\sequence{,}|_cons(|\emph{E\sub{n-1}}|,|\emph{E\subn}|)|\sequence{}|)
\end{lstlisting}
Conversely, a sequence may be `front' loaded and be defined by appending elements to a `front' expression:
\begin{lstlisting}[escapechar=|]
|\emph{Label}| of [|\emph{F}\q{..,}\emph{E\sub1}\sequence{,}\emph{E\subn}|]
\end{lstlisting}
is equivalent to the expression:
\begin{lstlisting}[escapechar=|]
_apnd(|\sequence{}|_apnd(|\emph{F}|,|\emph{E\sub1}|)|\sequence{}\emph{E\subn}|)
\end{lstlisting}
\begin{aside}
It is also possible to have a sequence expression is that is \emph{both} front-loaded and back-loaded:
\begin{lstlisting}[escapechar=|]
|\emph{Label}| of [|\emph{F}|..,|\emph{M}|,..|\emph{T}|]
\end{lstlisting}
is equivalent to:
\begin{lstlisting}[escapechar=|]
_apnd(_cons(|\emph{F}|,|\emph{M}|),|\emph{T}|)
\end{lstlisting}
which, in turn, is equivalent to:
\begin{lstlisting}[escapechar=|]
_cons(|\emph{F}|,_apnd(|\emph{M}|,|\emph{T}|))
\end{lstlisting}
\end{aside}
\subsubsection{Type Safety}
Since a sequence expression is essentially a macro for the use of the \q{sequence} contract, its type safety determined by the \q{sequence} contract in Program~\vref{sequenceContractDef}.
\section{Index and Slice Notation}
\label{indexNotation}
\index{index notation}
\index{notation for indexed access}
In a similar vein to the \ntRef{Sequence} notation, the \ntRef{IndexExp} notation provides a high-level notation for accessing elements and subsets of collections.
\begin{figure}[htbp]
\begin{eqnarray*}
\emph{Expression}&\arrowplus&\ntRef{IndexExp}\\
\ntDef{IndexExp}&\arrow&\ntRef{Index}\ \choice\ \ntRef{IndexWith}\ \choice\ \ntRef{Slice}\\
\ntDef{Index}&\arrow&\ntRef{Expression}\ \q{[}\,\ntRef{Expression}\q{]}\\
\ntDef{IndexWith}&\arrow&\ntRef{Expression}\ \q{[}\,\q{with}\ \ntRef{Expression}\,\q{->}\,\ntRef{Expression}\q{]}\\
&\choice&\ntRef{Expression}\ \q{[}\,\q{without}\ \ntRef{Expression}\,\q{]}\\
\ntDef{Slice}&\arrow&\ntRef{Expression}\ \q{[}\,\ntRef{Expression}\,\q{:}\,\ntRef{Expression}\,\q{]}\\
&\choice&\ntRef{Expression}\ \q{[}\,\ntRef{Expression}\,\q{:}\,\q{]}
\end{eqnarray*}
\caption{Index and Slice Expressions}
\label{indexExpressionFig}
\end{figure}
\begin{aside}
There is some subtlety in the interpretation of index expressions; depending on whether the \ntRef{IndexExp} is an expression, or whether it is the left hand side of an assignment:
\begin{lstlisting}
L[Ix] := E
\end{lstlisting}
In the sections that follow, and in Section~\vref{sequenceUpdate}, we show the different interpretations of an index expression.
\end{aside}
\subsection{Accessing Elements of a Collection}
\label{indexedAccess}
\index{indexed access to collection}
\index{access list with index}
An expression of the form:
\begin{lstlisting}
C[ix]
\end{lstlisting}
is equivalent to the expression
\begin{lstlisting}
_index(C,ix)
\end{lstlisting}
\begin{aside}