-
Notifications
You must be signed in to change notification settings - Fork 20
/
CheatSheet.lhs
1534 lines (1110 loc) · 49.7 KB
/
CheatSheet.lhs
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
\documentclass[11pt]{article}
%include lhs2TeX.fmt
\usepackage[T1]{fontenc}
\usepackage[sc]{mathpazo}
\linespread{1.05}
\usepackage{helvet}
\usepackage{multicol}
\usepackage{float}
\usepackage[landscape, top=0.2in, bottom=1in, left=0.2in, right=0.2in, dvips]{geometry}
\usepackage{verbatim}
\usepackage{fancyhdr}
\usepackage{paralist}
\usepackage{hyperref}
\usepackage[all]{hypcap} % Must be after hyperref
% \usepackage{setspace}
\hypersetup{colorlinks}
\pagestyle{fancy}
\fancyhf{}
\lfoot{\copyright\ 2010 Justin Bailey.}
\cfoot{\thepage}
\rfoot{\href{mailto:jgbailey@@codeslower.com}{\tt jgbailey@@codeslower.com}}
\renewcommand\footrulewidth{0.4pt}
\makeatletter
% Copied from article.cls; second-to-last parameter changed to -\parindent.
\renewcommand\subsubsection{\@@startsection{subsubsection}{3}{\z@@}%
{-3.25ex \@@plus -1ex \@@minus -.2ex}%
{-\parindent}%
{\normalfont\normalsize\bfseries}}
\makeatother
\newcommand{\hd}[1]{\section*{\textsf{#1}}}
\newcommand{\shd}[1]{\subsection*{\textsf{#1}}}
\newcommand{\sshd}[1]{\subsubsection*{\textsf{#1}}}
\setlength{\columnsep}{18.0pt}
\setlength{\columnseprule}{0.4pt}
\begin{document}
% \doublespacing
\begin{multicols}{3}
\section*{\textsf{\LARGE Haskell Cheat Sheet\normalsize}}\label{preamble}
This cheat sheet lays out the fundamental elements of the Haskell language:
syntax, keywords and other elements. It is presented as both an executable
Haskell file and a printable document. Load the source into your favorite
interpreter to play with code samples shown.
\begin{comment}
> {-# LANGUAGE MultiParamTypeClasses,NPlusKPatterns, DatatypeContexts #-}
>
> module CheatSheet where
>
> import Data.Char (isUpper, isLower, toUpper, toLower, isSpace, GeneralCategory(..))
> import System.IO (readFile)
> import System.Directory (doesFileExist)
> import qualified Data.Set as Set
> import qualified Data.Char as Char
\end{comment}
\hd{Basic Syntax}\label{syntax}
\shd{Comments}\label{comments}
A single line comment starts with `@--@' and extends to the end of the line.
Multi-line comments start with '@{-@' and extend to '@-}@'. Comments can be
nested.
Comments above function definitions should start with `@{- |@' and those next
to parameter types with `@-- ^@' for compatibility with
Haddock, a system for documenting
Haskell code.
\shd{Reserved Words}\label{reserved-words}
The following words are reserved in Haskell. It is a syntax error to give a
variable or a function one of these names.
\setlength{\columnsep}{10.0pt}
\setlength{\columnseprule}{0.0pt}
\begin{multicols}{3}
\begin{compactitem}
\item @case@
\item @class@
\item @data@
\item @deriving@
\item @do@
\item @else@
\item @if@
\item @import@
\item @in@
\item @infix@
\item @infixl@
\item @infixr@
\item @instance@
\item @let@
\item @of@
\item @module@
\item @newtype@
\item @then@
\item @type@
\item @where@
\end{compactitem}
\end{multicols}
\setlength{\columnsep}{18.0pt}
\setlength{\columnseprule}{0.4pt}
\shd{Strings}\label{strings}
\begin{compactitem}
\item @"abc"@ -- Unicode string, sugar for @['a','b','c']@.
\item @'a'@ -- Single character.
\end{compactitem}
\sshd{Multi-line Strings}\label{multi-line-strings}
Normally, it is a syntax error if a string has any newline characters.
That is, this is a syntax error:
< string1 = "My long
< string."
Backslashes (`@\@') can ``escape'' a newline:
> string1 = "My long \
> \string."
The area between the backslashes is ignored. Newlines \emph{in} the
string must be represented explicitly:
> string2 = "My long \n\
> \string."
That is, @string1@ evaluates to:
< My long string.
While @string2@ evaluates to:
< My long
< string.
\sshd{Escape Codes} The following escape codes can be used in characters or strings:
\begin{compactitem}
\item @\n@, @\r@, @\f@, etc. -- The standard codes for newline,
carriage return, form feed, etc. are supported.
\item @\72@, @\x48@, @\o110@ -- A character with the value 72 in
decimal, hex and octal, respectively.
\item @\&@ -- A ``null'' escape character which allows numeric
escape codes next to numeric literals. For example, @\x2C4@ is
$\wedge$ (in Unicode) while @\x2C\&4@ is @,4@. This sequence
cannot be used in character literals.
\end{compactitem}
\shd{Numbers}\label{numbers}
\begin{compactitem}
\item @1@ -- Integer or floating point value.
\item @1.0, 1e10@ -- Floating point value.
\item @0o1, 0O1@ -- Octal value.
\item @0x1, 0X1@ -- Hexadecimal value.
\item @-1@ -- Negative number; the minus sign (``@-@'') cannot be separated from the number.
\end{compactitem}
\shd{Enumerations}\label{enumerations}
\begin{compactitem}
\item @[1..10]@ -- List of numbers -- \texttt{1, 2, {\ensuremath\mathellipsis}, 10}.
\item @[100..]@ -- Infinite list of numbers -- \texttt{100, 101, 102, {\ensuremath\mathellipsis}\ }.
\item @[110..100]@ -- Empty list, but @[110, 109 .. 100]@ will give a list from 110 to 100.
\item @[0, -1 ..]@ -- Negative integers.
\item @[-110..-100]@ -- Syntax error; need @[-110.. -100]@ for negatives.
\item @[1,3..99], [-1,3..99]@ -- List from 1 to 99 by 2, -1 to 99 by 4.
\end{compactitem}
\noindent In fact, any value which is in the @Enum@ class can be used:
\begin{compactitem}
\item @['a' .. 'z']@ -- List of characters -- \texttt{a, b, {\ensuremath\mathellipsis}, z}.
\item @['z', 'y' .. 'a']@ -- \texttt{z, y, x, {\ensuremath\mathellipsis}, a}.
\item @[1.0, 1.5 .. 2]@ -- @[1.0,1.5,2.0]@.
\item @[UppercaseLetter ..]@ -- List of @GeneralCategory@ values (from @Data.Char@).
\end{compactitem}
\shd{Lists \& Tuples}\label{lists-tuples}
\begin{compactitem}
\item @[]@ -- Empty list.
\item @[1,2,3]@ -- List of three numbers.
\item @1 : 2 : 3 : []@ -- Alternate way to write lists using ``cons'' (@:@) and ``nil'' (@[]@).
\item @"abc"@ -- List of three characters (strings are lists).
\item @'a' : 'b' : 'c' : []@ -- List of characters (same as @"abc"@).
\item @(1,"a")@ -- 2-element tuple of a number and a string.
\item @(head, tail, 3, 'a')@ -- 4-element tuple of two functions, a number and a character.
\end{compactitem}
\shd{``Layout'' rule, braces and semi-colons.}\label{layout}
Haskell can be written using braces and semi-colons, just like C. However, no
one does. Instead, the ``layout'' rule is used, where spaces represent scope.
The general rule is: always indent. When the compiler complains, indent more.
\sshd{Braces and semi-colons}\label{braces-semicolons}
Semi-colons terminate an expression, and braces represent scope. They can be
used after several keywords: @where@, @let@, @do@ and @of@. They cannot be
used when defining a function body. For example, the below will not compile.
< square2 x = { x * x; }
However, this will work fine:
> square2 x = result
> where { result = x * x; }
\sshd{Function Definition}\label{layout-function-definition}
Indent the body at least one space from the function name:
< square x =
< x * x
Unless a @where@ clause is present. In that case, indent the where clause at
least one space from the function name and any function bodies at least one
space from the @where@ keyword:
< square x =
< x2
< where x2 =
< x * x
\sshd{Let}\label{layout-let}
Indent the body of the let at least one space from the first definition in the
@let@. If @let@ appears on its own line, the body of any definition must
appear in the column after the let:
< square x =
< let x2 =
< x * x
< in x2
As can be seen above, the @in@ keyword must also be in the same column as
@let@. Finally, when multiple definitions are given, all identifiers must
appear in the same column.
\hd{Declarations, Etc.}\label{declarations}
The following section details rules on function declarations, list
comprehensions, and other areas of the language.
\shd{Function Definition}\label{function-definition}
Functions are defined by declaring their name, any arguments, and an equals
sign:
> square x = x * x
\emph{All} functions names must start with a lowercase letter or ``@_@''. It
is a syntax error otherwise.
\sshd{Pattern Matching}\label{pattern-matching}
Multiple ``clauses'' of a function can be defined by ``pattern-matching'' on
the values of arguments. Here, the @agree@ function has four separate
cases:
> -- Matches when the string "y" is given.
> agree1 "y" = "Great!"
> -- Matches when the string "n" is given.
> agree1 "n" = "Too bad."
> -- Matches when string beginning
> -- with 'y' given.
> agree1 ('y':_) = "YAHOO!"
> -- Matches for any other value given.
> agree1 _ = "SO SAD."
Note that the `@_@' character is a wildcard and matches any value.
Pattern matching can extend to nested values. Assuming this data declaration:
< data Bar = Bil (Maybe Int) | Baz
\noindent and recalling the \hyperref[maybe]{definition of @Maybe@} from
page~\pageref{maybe} we can match on nested @Maybe@ values when @Bil@ is
present:
< f (Bil (Just _)) = ...
< f (Bil Nothing) = ...
< f Baz = ...
Pattern-matching also allows values to be assigned to variables. For example,
this function determines if the string given is empty or not. If not, the
value bound to @str@ is converted to lower case:
> toLowerStr [] = []
> toLowerStr str = map toLower str
Note that @str@ above is similar to @_@ in that it will match anything; the
only difference is that the value matched is also given a name.
\sshd{{\ensuremath $n + k$} Patterns}\label{plus-patterns}
This (sometimes controversial) pattern-matching facility makes it easy to match
certain kinds of numeric expressions. The idea is to define a base case (the
``$n$'' portion) with a constant number for matching, and then to define other
matches (the ``$k$'' portion) as additives to the base case. Here is a rather
inefficient way of testing if a number is even or not:
> isEven 0 = True
> isEven 1 = False
> isEven (n + 2) = isEven n
\sshd{Argument Capture}\label{argument-capture}
Argument capture is useful for pattern-matching a value \emph{and} using it,
without declaring an extra variable. Use an `|@|' symbol in between the
pattern to match and the variable to bind the value to. This facility is
used below to bind the head of the list in @l@ for display, while also
binding the entire list to @ls@ in order to compute its length:
> len ls@(l:_) = "List starts with " ++
> show l ++ " and is " ++
> show (length ls) ++ " items long."
> len [] = "List is empty!"
\sshd{Guards}\label{function-guards}
Boolean functions can be used as ``guards'' in function definitions along with
pattern matching. An example without pattern matching:
> which n
> | n == 0 = "zero!"
> | even n = "even!"
> | otherwise = "odd!"
Notice @otherwise@ -- it always evaluates to @True@ and can be used to specify
a ``default'' branch.
Guards can be used with patterns. Here is a function that determines if the
first character in a string is upper or lower case:
> what [] = "empty string!"
> what (c:_)
> | isUpper c = "upper case!"
> | isLower c = "lower case"
> | otherwise = "not a letter!"
\sshd{Matching \& Guard Order}\label{function-matching-order}
Pattern-matching proceeds in top to bottom order. Similarly, guard expressions
are tested from top to bottom. For example, neither of these functions would
be very interesting:
> allEmpty _ = False
> allEmpty [] = True
>
> alwaysEven n
> | otherwise = False
> | n `div` 2 == 0 = True
\sshd{Record Syntax}\label{matching-record-syntax}
Normally pattern matching occurs based on the position of arguments in the
value being matched. Types declared with record syntax, however, can match
based on those record names. Given this data type:
> data Color = C { red
> , green
> , blue :: Int }
\begin{comment}
> deriving (Show, Eq)
\end{comment}
\noindent we can match on @green@ only:
> isGreenZero (C { green = 0 }) = True
> isGreenZero _ = False
Argument capture is possible with this syntax, although it gets clunky.
Continuing the above, we now define a @Pixel@ type and a function to replace
values with non-zero @green@ components with all black:
> data Pixel = P Color
\begin{comment}
> deriving (Show, Eq)
\end{comment}
> -- Color value untouched if green is 0
> setGreen (P col@(C { green = 0 })) = P col
> setGreen _ = P (C 0 0 0)
\sshd{Lazy Patterns}\label{lazy-patterns}
This syntax, also known as \emph{irrefutable} patterns, allows pattern matches
which always succeed. That means any clause using the pattern will succeed,
but if it tries to actually use the matched value an error may occur. This is
generally useful when an action should be taken on the \emph{type} of a
particular value, even if the value isn't present.
For example, define a class for default values:
> class Def a where
> defValue :: a -> a
The idea is you give @defValue@ a value of the right type and it gives you
back a default value for that type. Defining instances for basic types is
easy:
> instance Def Bool where
> defValue _ = False
>
> instance Def Char where
> defValue _ = ' '
@Maybe@ is a littler trickier, because we want to get a default value for the
type, but the constructor might be @Nothing@. The following definition would
work, but it's not optimal since we get @Nothing@ when @Nothing@ is passed in.
< instance Def a => Def (Maybe a) where
< defValue (Just x) = Just (defValue x)
< defValue Nothing = Nothing
We'd rather get a {\tt Just (\rm\emph{default value}\tt)\rm} back instead.
Here is where a lazy pattern saves us -- we can pretend that we've matched
@Just x@ and use that to get a default value, even if @Nothing@ is given:
> instance Def a => Def (Maybe a) where
> defValue ~(Just x) = Just (defValue x)
As long as the value @x@ is not actually evaluated, we're safe. None of the
base types need to look at @x@ (see the ``@_@'' matches they use), so things
will work just fine.
One wrinkle with the above is that we must provide type annotations in the
interpreter or the code when using a @Nothing@ constructor. @Nothing@ has type
@Maybe a@ but, if not enough other information is available, Haskell must be
told what @a@ is. Some example default values:
> -- Return "Just False"
> defMB = defValue (Nothing :: Maybe Bool)
> -- Return "Just ' '"
> defMC = defValue (Nothing :: Maybe Char)
\shd{List Comprehensions}\label{list-comprehensions}
A list comprehension consists of four types of elements: \emph{generators},
\emph{guards}, \emph{local bindings}, and \emph{targets}. A list comprehension
creates a list of target values based on the generators and guards given. This
comprehension generates all squares:
> squares = [x * x | x <- [1..]]
@x <- [1..]@ generates a list of all @Integer@ values and puts them in @x@,
one by one. @x * x@ creates each element of the list by multiplying @x@ by
itself.
Guards allow certain elements to be excluded. The following shows how divisors
for a given number (excluding itself) can be calculated. Notice how @d@ is
used in both the guard and target expression.
> divisors n =
> [d | d <- [1..(n `div` 2)]
> , n `mod` d == 0]
Local bindings provide new definitions for use in the generated expression or
subsequent generators and guards. Below, @z@ is used to represent the minimum
of @a@ and @b@:
> strange = [(a,z) | a <-[1..3]
> , b <-[1..3]
> , c <- [1..3]
> , let z = min a b
> , z < c ]
Comprehensions are not limited to numbers. Any list will do. All upper case
letters can be generated:
> ups =
> [c | c <- [minBound .. maxBound]
> , isUpper c]
Or, to find all occurrences of a particular break value @br@ in a list @word@
(indexing from 0):
> idxs word br =
> [i | (i, c) <- zip [0..] word
> , c == br]
A unique feature of list comprehensions is that pattern matching failures do
not cause an error; they are just excluded from the resulting list.
\shd{Operators}\label{operators}
There are very few predefined ``operators'' in Haskell---most that appear
predefined are actually syntax (e.g., ``@=@''). Instead, operators are simply
functions that take two arguments and have special syntactic support. Any
so-called operator can be applied as a prefix function using parentheses:
< 3 + 4 == (+) 3 4
To define a new operator, simply define it as a normal function, except the
operator appears between the two arguments. Here's one which inserts a
comma between two strings and ensures no extra spaces appear:
> first ## last =
> let trim s = dropWhile isSpace
> (reverse (dropWhile isSpace
> (reverse s)))
> in trim last ++ ", " ++ trim first
< > " Haskell " ## " Curry "
< Curry, Haskell
Of course, full pattern matching, guards, etc. are available in this form.
Type signatures are a bit different, though. The operator ``name'' must appear
in parentheses:
> (##) :: String -> String -> String
Allowable symbols which can be used to define operators are:
< # $ % & * + . / < = > ? @ \ ^ | - ~
However, there are several ``operators'' which cannot be redefined. They are:
@<-@, @->@ and @=@. The last, @=@, cannot be redefined by itself, but can be
used as part of multi-character operator. The ``bind'' function, @>>=@, is one
example.
\sshd{Precedence \& Associativity}\label{fixity}
The precedence and associativity, collectively called \emph{fixity}, of any
operator can be set through the @infix@, @infixr@ and @infixl@ keywords. These
can be applied both to top-level functions and to local definitions. The
syntax is:
\bigskip
\textbraceleft\texttt{infix} || \texttt{infixr} || \texttt{infixl}\textbraceright\ \emph{precedence op}
\bigskip
\noindent where \emph{precedence} varies from 0 to 9. \emph{Op} can actually
be any function which takes two arguments (i.e., any binary operation).
Whether the operator is left or right associative is specified by @infixl@ or
@infixr@, respectively. Such @infix@ declarations have no associativity.
Precedence and associativity make many of the rules of arithmetic work ``as
expected.'' For example, consider these minor updates to the precedence of
addition and multiplication:
> infixl 8 `plus1`
> plus1 a b = a + b
> infixl 7 `mult1`
> mult1 a b = a * b
The results are surprising:
< > 2 + 3 * 5
< 17
< > 2 `plus1` 3 `mult1` 5
< 25
Reversing associativity also has interesting effects. Redefining division as
right associative:
> infixr 7 `div1`
> div1 a b = a / b
We get interesting results:
< > 20 / 2 / 2
< 5.0
< > 20 `div1` 2 `div1` 2
< 20.0
\shd{Currying}\label{currying}
In Haskell, functions do not have to get all of their arguments at once. For
example, consider the @convertOnly@ function, which only converts certain
elements of string depending on a test:
> convertOnly test change str =
> map (\c -> if test c
> then change c
> else c) str
Using @convertOnly@, we can write the @l33t@ function which converts certain
letters to numbers:
> l33t = convertOnly isL33t toL33t
> where
> isL33t 'o' = True
> isL33t 'a' = True
> -- etc.
> isL33t _ = False
> toL33t 'o' = '0'
> toL33t 'a' = '4'
> -- etc.
> toL33t c = c
Notice that @l33t@ has no arguments specified. Also, the final argument to
@convertOnly@ is not given. However, the type signature of @l33t@ tells the
whole story:
< l33t :: String -> String
That is, @l33t@ takes a string and produces a string. It is a ``constant'', in
the sense that @l33t@ always returns a value that is a function which takes a
string and produces a string. @l33t@ returns a ``curried'' form of
@convertOnly@, where only two of its three arguments have been supplied.
This can be taken further. Say we want to write a function which only changes
upper case letters. We know the test to apply, @isUpper@, but we don't want to
specify the conversion. That function can be written as:
> convertUpper = convertOnly isUpper
which has the type signature:
< convertUpper :: (Char -> Char)
< -> String -> String
That is, @convertUpper@ can take two arguments. The first is the conversion
function which converts individual characters and the second is the string to
be converted.
A curried form of any function which takes multiple arguments can be created.
One way to think of this is that each ``arrow'' in the function's signature
represents a new function which can be created by supplying one more argument.
\sshd{Sections}\label{sections}
Operators are functions, and they can be curried like any other. For example, a
curried version of ``@+@'' can be written as:
< add10 = (+) 10
However, this can be unwieldy and hard to read. ``Sections'' are curried
operators, using parentheses. Here is @add10@ using sections:
> add10 = (10 +)
The supplied argument can be on the right or left, which indicates what
position it should take. This is important for operations such as
concatenation:
> onLeft str = (++ str)
> onRight str = (str ++)
Which produces quite different results:
< > onLeft "foo" "bar"
< "barfoo"
< > onRight "foo" "bar"
< "foobar"
\shd{``Updating'' values and record syntax}\label{updating}
Haskell is a pure language and, as such, has no mutable state. That is, once a
value is set it never changes. ``Updating'' is really a copy operation, with
new values in the fields that ``changed.'' For example, using the @Color@ type
defined earlier, we can write a function that sets the @green@ field to zero
easily:
> noGreen1 (C r _ b) = C r 0 b
The above is a bit verbose and can be rewritten using record syntax. This kind
of ``update'' only sets values for the field(s) specified and copies the rest:
> noGreen2 c = c { green = 0 }
Here we capture the @Color@ value in @c@ and return a new @Color@ value. That
value happens to have the same value for @red@ and @blue@ as @c@ and it's
@green@ component is 0. We can combine this with pattern matching to set the
@green@ and @blue@ fields to equal the @red@ field:
> makeGrey c@(C { red = r }) =
> c { green = r, blue = r }
Notice we must use argument capture (``|c@|'') to get the @Color@ value and
pattern matching with record syntax (``|C { red = r}|'') to get the inner
@red@ field.
\shd{Anonymous Functions}\label{anonymous-functions}
An anonymous function (i.e., a \emph{lambda expression} or \emph{lambda} for
short), is a function without a name. They can be defined at any time like so:
< \c -> (c, c)
which defines a function that takes an argument and returns a tuple
containing that argument in both positions. They are useful for simple
functions which don't need a name. The following determines if a string
consists only of mixed case letters and whitespace.
> mixedCase str =
> all (\c -> isSpace c ||
> isLower c ||
> isUpper c) str
Of course, lambdas can be the returned from functions too. This classic
returns a function which will then multiply its argument by the one originally
given:
> multBy n = \m -> n * m
For example:
< > let mult10 = multBy 10
< > mult10 10
< 100
\shd{Type Signatures}\label{type-signatures}
Haskell supports full type inference, meaning in most cases no types have to
be written down. Type signatures are still useful for at least two reasons.
\begin{description}
\item{\emph{Documentation}}---Even if the compiler can figure out the types
of your functions, other programmers or even yourself might not be able to
later. Writing the type signatures on all top-level functions is considered
very good form.
\item{\emph{Specialization}}---Typeclasses allow functions with overloading.
For example, a function to negate any list of numbers has the signature:
< negateAll :: Num a => [a] -> [a]
However, for efficiency or other reasons you may only want to allow @Int@
types. You would accomplish that with a type signature:
< negateAll :: [Int] -> [Int]
\end{description}
Type signatures can appear on top-level functions and nested @let@ or @where@
definitions. Generally this is useful for documentation, although in some
cases they are needed to prevent polymorphism. A type signature is first the
name of the item which will be typed, followed by a @::@, followed by the
types. An example of this has already been seen above.
Type signatures do not need to appear directly above their implementation.
They can be specified anywhere in the containing module (yes, even below!).
Multiple items with the same signature can also be defined together:
> pos, neg :: Int -> Int
< ...
> pos x | x < 0 = negate x
> | otherwise = x
>
> neg y | y > 0 = negate y
> | otherwise = y
\sshd{Type Annotations}\label{type-annotations}
Sometimes Haskell cannot determine what type is meant. The classic
demonstration of this is the so-called ``@show . read@'' problem:
< canParseInt x = show (read x)
Haskell cannot compile that function because it does not know the type of @read x@.
We must limit the type through an annotation:
> canParseInt x = show (read x :: Int)
Annotations have the same syntax as type signatures, but may adorn
any expression. Note that the annotation above is on the expression
@read x@, not on the variable @x@. Only function application (e.g.,
@read x@) binds tighter than annotations. If that was not the case,
the above would need to be written @(read x) :: Int@.
\shd{Unit}\label{unit}
@()@ -- ``unit'' type and ``unit'' value. The value and type that represents
no useful information.
\hd{Keywords}\label{keywords}
Haskell keywords are listed below, in alphabetical order.
\shd{Case}\label{case}
@case@ is similar to a @switch@ statement in C\# or Java, but can match a
pattern: the shape of the value being inspected. Consider a simple data type:
> data Choices = First String | Second |
> Third | Fourth
\begin{comment}
> deriving (Show, Eq)
\end{comment}
\noindent @case@ can be used to determine which choice was given:
> whichChoice ch =
> case ch of
> First _ -> "1st!"
> Second -> "2nd!"
> _ -> "Something else."
As with pattern-matching in function definitions, the `@_@' token is a
``wildcard'' matching any value.
\sshd{Nesting \& Capture}\label{nesting-capture}
Nested matching and binding are also allowed. For example, here is the definition
of the @Maybe@ type:
< data Maybe a = Just a | Nothing
\label{maybe}
Using @Maybe@ we can determine if any choice was given using a nested match:
> anyChoice1 ch =
> case ch of
> Nothing -> "No choice!"
> Just (First _) -> "First!"
> Just Second -> "Second!"
> _ -> "Something else."
Binding can be used to manipulate the value matched:
> anyChoice2 ch =
> case ch of
> Nothing -> "No choice!"
> Just score@(First "gold") ->
> "First with gold!"
> Just score@(First _) ->
> "First with something else: "
> ++ show score
> _ -> "Not first."
\sshd{Matching Order}\label{case-matching-order}
Matching proceeds from top to bottom. If @anyChoice1@ is reordered as follows,
the first pattern will always succeed:
> anyChoice3 ch =
> case ch of
> _ -> "Something else."
> Nothing -> "No choice!"
> Just (First _) -> "First!"
> Just Second -> "Second!"
\sshd{Guards}\label{case-guards}
Guards, or conditional matches, can be used in cases just like function
definitions. The only difference is the use of the @->@ instead of @=@. Here
is a simple function which does a case-insensitive string match:
> strcmp s1 s2 = case (s1, s2) of
> ([], []) -> True
> (s1:ss1, s2:ss2)
> | toUpper s1 == toUpper s2 ->
> strcmp ss1 ss2
> | otherwise -> False
> _ -> False
\shd{Class}\label{class}
A Haskell function is defined to work on a certain type or set of types and
cannot be defined more than once. Most languages support the idea of
``overloading'', where a function can have different behavior depending on the
type of its arguments. Haskell accomplishes overloading through @class@ and
@instance@ declarations. A @class@ defines one or more functions that can be
applied to any types which are members (i.e., instances) of that class. A
class is analogous to an interface in Java or C\#, and instances to a concrete
implementation of the interface.
A class must be declared with one or more type variables. Technically, Haskell
98 only allows one type variable, but most implementations of Haskell support
so-called \emph{multi-parameter type classes}, which allow more than one type
variable.
We can define a class which supplies a flavor for a given type:
> class Flavor a where
> flavor :: a -> String
Notice that the declaration only gives the type signature of the function---no
implementation is given here (with some exceptions, see
\hyperref[defaults]{``Defaults''} on page~\pageref{defaults}). Continuing, we
can define several instances:
> instance Flavor Bool where
> flavor _ = "sweet"
>
> instance Flavor Char where
> flavor _ = "sour"
Evaluating @flavor True@ gives:
< > flavor True
< "sweet"
While @flavor 'x'@ gives:
< > flavor 'x'
< "sour"
\sshd{Defaults}\label{defaults}
Default implementations can be given for functions in a class. These are
useful when certain functions can be defined in terms of others in the class.
A default is defined by giving a body to one of the member functions. The
canonical example is @Eq@, which defines @/=@ (not equal) in terms of @==@\ :
< class Eq a where
< (==) :: a -> a -> Bool
< (/=) :: a -> a -> Bool
< (/=) a b = not (a == b)
Recursive definitions can be created. Continuing the @Eq@ example,
@==@ can be defined in terms of @/=@:
< (==) a b = not (a /= b)
However, if instances do not provide enough concrete implementations
of member functions then any program using those instances will loop.
\shd{Data}\label{data}
So-called \emph{algebraic data types} can be declared as follows:
> data MyType = MyValue1 | MyValue2
\begin{comment}
> deriving (Show, Eq)
\end{comment}
@MyType@ is the type's \emph{name}. @MyValue1@ and @MyValue2@ are \emph{values}
of the type and are called \emph{constructors}. Multiple constructors are
separated with the `@|@' character. Note that type and constructor names
\emph{must} start with a capital letter. It is a syntax error otherwise.
\sshd{Constructors with Arguments}\label{constructors-with-arguments}
The type above is not very interesting except as an enumeration. Constructors
that take arguments can be declared, allowing more information to be stored:
> data Point = TwoD Int Int
> | ThreeD Int Int Int
Notice that the arguments for each constructor are \emph{type} names, not
constructors. That means this kind of declaration is illegal:
< data Poly = Triangle TwoD TwoD TwoD
instead, the @Point@ type must be used:
> data Poly = Triangle Point Point Point
\sshd{Type and Constructor Names}\label{type-punning}
Type and constructor names can be the same, because they will never be used in
a place that would cause confusion. For example:
> data User = User String | Admin String
which declares a type named @User@ with two constructors, @User@ and @Admin@.
Using this type in a function makes the difference clear:
> whatUser (User _) = "normal user."
> whatUser (Admin _) = "admin user."
Some literature refers to this practice as \emph{type punning}.
\sshd{Type Variables}\label{type-variables}
Declaring so-called \emph{polymorphic} data types is as easy as adding type
variables in the declaration:
> data Slot1 a = Slot1 a | Empty1
This declares a type @Slot1@ with two constructors, @Slot1@ and @Empty1@. The
@Slot1@ constructor can take an argument of \emph{any} type, which is
represented by the type variable @a@ above.
We can also mix type variables and specific types in constructors:
> data Slot2 a = Slot2 a Int | Empty2
Above, the @Slot2@ constructor can take a value of any type and an @Int@
value.
\sshd{Record Syntax}\label{record-syntax}