This repository was archived by the owner on Nov 1, 2018. It is now read-only.
forked from haskell-lisp/yale-haskell
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtutorial.hs
2143 lines (1556 loc) · 67.6 KB
/
tutorial.hs
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
-- Page 0 Introduction
This is a programming supplement to `A Gentle Introduction to Haskell'
by Hudak and Fasel. This supplement augments the tutorial by
providing executable Haskell programs which you can run and
experiment with. All program fragments in the tutorial are
found here, as well as other examples not included in the tutorial.
Using This Tutorial
You should have a copy of both the `Gentle Introduction' and the
report itself to make full use of this tutorial. Although the
`Gentle Introduction' is meant to stand by itself, it is often easier
to learn a language through actual use and experimentation than by
reading alone. Once you finish this introduction, we recommend that
you proceed section by section through the `Gentle Introduction' and
after having read each section go back to this online tutorial. You
should wait until you have finished the tutorial before attempting to
read the report. We assume that you are familiar with the basics of
Emacs and that Haskell has been installed at your site.
This tutorial does not assume any familiarity with Haskell or other
functional languages. However, knowledge of almost-functional
languages such as ML or Scheme is very useful. Throughout the
online component of this tutorial, we try to relate Haskell to
other programming languages and clarify the written tutorial through
additional examples and text.
Organization of the Online Tutorial
This online tutorial is divided into a series of pages. Each page
covers one or more sections in the written tutorial. You can use
special Emacs commands to move back and forth through the pages of the
online tutorial. Each page is a single Haskell program. Comments in
the program contain the text of the online tutorial. You can modify
the program freely (this will not change the underlying tutorial
file!) and ask the system to print the value of expressions defined in
the program.
At the beginning of each page, the sections covered by the page are
listed. In addition, the start of each individual section is
marked within each page. Emacs commands can take you directly to a
specific page or section in the tutorial.
To create useful, executable examples of Haskell code, some language
constructs need to be revealed well before they are explained in the
tutorial. We attempt to point these out when they occur. Some
small changes have been made to the examples in the written tutorial;
these are usually cosmetic and should be ignored. Don't feel you have
to understand everything on a page before you move on -- many times
concepts become clearer as you move on and can relate them to other
aspect of the language.
Each page of the tutorial defines a set of variables. Some of
these are named e1, e2, and so on. These `e' variables are the ones
which are meant for you to evaluate as you go through the tutorial.
Of course you may evaluate any other expressions or variables you wish.
The Haskell Report
While the report is not itself a tutorial on the Haskell language, it
can be an invaluable reference to even a novice user. A very
important feature of Haskell is the prelude. The prelude is a
rather large chunk of Haskell code which is implicitly a part of every
Haskell program. Whenever you see functions used which are not
defined in the current page, these come from the Prelude. Appendix A
of the report lists the entire Prelude; the index has an entry for
every function in the Prelude. Looking at the definitions in the
Prelude is sometimes necessary to fully understand the programs in
this tutorial.
Another reason to look at the report is to understand the syntax of
Haskell. Appendix B contains the complete syntax for Haskell. The
tutorial treats the syntax very informally; the precise details are
found only in the report.
The Yale Haskell System
This version of the tutorial runs under version Y2.0 of Yale Haskell.
The Yale Haskell system is an interactive programming environment for
the Haskell language. The system is best used in conjunction with the
Emacs editor. Yale Haskell is available free of change via ftp.
Using the Compiler
Yale Haskell runs as a subprocess under Emacs. While many commands
are available to the Yale Haskell user, a single command is the
primary means of communicating with the compiler: C-c e. This command
evaluates and prints an expression in the context of the program on
the screen. Here is what this command does:
a) You are prompted for an expression in the minibuffer. You can
use M-p or M-n to move through a ring of previous inputs.
b) If an inferior Haskell process is not running, a buffer named *haskell*
is created and the Haskell compiler is started up. The *haskell* buffer
pops onto your screen.
c) If the program in the current page of the tutorial has not yet been
compiled or the page has been modified after its most recent
compilation, the entire page is compiled. This may result in a short delay.
d) If there are no errors in the program, the expression entered in
step a) is compiled in the context of the program. Any value defined
in the current page can be referenced.
e) If there are no errors in the expression, its value is printed in
the *haskell* buffer.
There are also a few other commands you can use. C-c i interrupts
the Haskell program. Some tight loops cannot be interrupted; in this
case you will have to kill the Haskell process. C-c q exits the Haskell
process.
Emacs Commands Used by the Tutorial
These commands are specific to the tutorial. The tutorial is entered
using M-x haskell-tutorial and is exited with C-c q. To move among
the pages of the tutorial, use
C-c C-f -- go forward 1 page
C-c C-b -- go back 1 page
M-x ht-goto-page - goto a specific page of the tutorial
M-x ht-goto-section - goto a specific section of the tutorial
Each page of the tutorial can be modified without changing the
underlying text of the tutorial. Changes are not saved as you go
between pages. To revert a page to its original form use C-c C-l.
You can get help regarding the Emacs commands with C-c ?.
Summary of Emacs commands used by the tutorial:
M-x haskell-tutorial - start the tutorial
C-c C-f - Go to the next page of the tutorial program
C-c C-b - Go back to the previous page of the tutorial program
C-c C-l - Restore the current page to its original form
C-c e - Evaluate a Haskell expression
C-c i - Interrupt a running Haskell program
C-c ? - Shows a help message
M-x ht-goto-page - goto a specific page of the tutorial
M-x ht-goto-section - goto a specific section of the tutorial
You are now ready to start the tutorial. Start by reading the `Gentle
Introduction' section 1 then proceed through the online tutorial using
C-c C-f to advance to the next page. You should read about each topic
first before turning to the associated programming example in the
online tutorial.
-- Page 1 Section 2
-- Section 2 Values, Types, and Other Goodies
-- Haskell uses `--' to designate end of line comments. We use these
-- throughout the tutorial to place explanatory text in the program.
-- Remember to use C-c e to evaluate expressions, C-c ? for help.
-- All Haskell programs must start with a module declaration. Ignore this
-- for now.
module Test(Bool) where
-- We will start by defining some identifiers (variables) using equations.
-- You can print out the value of an identifier by typing C-c e and
-- typing the name of the identifier you wish to evaluate. This will
-- compile the entire program, not just the line with the definition
-- you want to see. Not all definitions are very interesting to print out -
-- by convention, we will use variables e1, e2, ... to denote values that
-- are `interesting' to print.
-- We'll start with some constants as well as their associated type.
-- There are two ways to associate a type with a value: a type declaration
-- and an expression type signature. Here is an equation and a type
-- declaration:
e1 :: Int -- This is a type declaration for the identifier e1
e1 = 5 -- This is an equation defining e1
-- You can evaluate the expression e1 and watch the system print `5'! Wow!
-- Remember that C-c e is prompting for an expression. Expressions like
-- e1 or 5 or 1+1 are all valid. However, `e1 = 5' is a definition,
-- not an expression. Trying to evaluate it will result in a syntax error.
-- The type declaration for e1 is not really necessary but we will try to
-- always provide type declarations for values to help document the program
-- and to ensure that the system infers the same type we do for an expression.
-- If you change the value for e1 to `True', the program will no longer
-- compile due to the type mismatch.
-- We will briefly mention expression type signatures: these are attached to
-- expressions instead of identifiers. Here are equivalent ways to do
-- the previous definition:
e2 = 5 :: Int
e3 = (2 :: Int) + (3 :: Int)
-- The :: has very low precedence in expressions and should usually be placed
-- in parenthesis.
-- Note that there are two completely separate languages: an expression
-- language for values and a type language for type signatures. The type
-- language is used only in the type declarations previously described and
-- declarations of new types, described later. Haskell uses a
-- uniform syntax so that values resemble their type signature as much as
-- possible. However, you must always be aware of the difference between
-- type expressions and value expressions.
-- Here are some of the predefined types Haskell provides:
-- type Value Syntax Type Syntax
-- Small integers <digits> Int
e4 :: Int
e4 = 12345
-- Characters '<character>' Char
e5 :: Char
e5 = 'a'
-- Boolean True, False Bool
e6 :: Bool
e6 = True
-- Floating point <digits.digits> Float
e7 :: Float
e7 = 123.456
-- We will introduce these types now; there will be much more to say later.
-- Homogenous List [<exp1>,<exp2>,...] [<constituant type>]
e8 :: [Int]
e8 = [1,2,3]
-- Tuple (<exp1>,<exp2>,...) (<exp1-type>,<exp2-type>,...)
e9 :: (Char,Int)
e9 = ('b',4)
-- Functional described later domain type -> range type
succ :: Int -> Int -- a function which takes an Int argument and returns Int
succ x = x + 1 -- test this by evaluating `succ 4'
-- Here's a few leftover examples from section 2:
e10 = succ (succ 3) -- you could also evaluate `succ (succ 3)' directly
-- by entering the entire expression to the C-c e
-- If you want to evaluate something more complex than the `e' variables
-- defined here, it is better to enter a complex expression, such as
-- succ (succ 3), directly than to edit a new definition like e10 into
-- the program. This is because any change to the program will require
-- recompilation of the entire page. The expressions entered to C-c e are
-- compiled separately (and very quickly!).
-- Uncomment this next line to see a compile time type error.
-- e11 = 'a'+'b'
-- Don't worry about the error message - it will make more sense later.
-- Proceed to the next page using C-c C-f
-- Page 2 Section 2.1
-- Section 2.1 Polymorphic Types
module Test(Bool) where
-- The following line allows us to redefine functions in the standard
-- prelude. Ignore this for now.
import Prelude hiding (length,head,tail,null)
-- start with some sample lists to use in test cases
list1 :: [Int]
list1 = [1,2,3]
list2 :: [Char] -- This is the really a string
list2 = ['a','b','c'] -- This is the same as "abc"; evaluate list2 and see.
list3 :: [[a]] -- The element type of the inner list is unknown
list3 = [[],[],[],[]] -- so this list can't be printed
list4 :: [Int]
list4 = 1:2:3:4:[] -- Exactly the same as [1,2,3,4]; print it and see.
-- This is the length function. You can test it by evaluating expressions
-- such as `length list1'. Function application is written by
-- simple juxtaposition: `f(x)' in other languages would be `f x' in Haskell.
length :: [a] -> Int
length [] = 0
length (x:xs) = 1 + length xs
-- Function application has the highest precedence, so 1 + length xs is
-- parsed as 1 + (length xs). In general, you have to surround
-- non-atomic arguments to a function with parens. This includes
-- arguments which are also function applications. For example,
-- f g x is the function f applied to arguments g and x, similar to
-- f(g,x) in other languages. However, f (g x) is f applied to (g x), or
-- f(g(x)), which means something quite different! Be especially
-- careful with infix operators: f x+1 y-2 would be parsed as (f x)+(1 y)-2.
-- This is also true on the left of the `=': the parens around (x:xs) are
-- absolutely necessary. length x:xs would be parsed as (length x):xs.
-- Also be careful with prefix negation, -. The application `f -1' is
-- f-1, not f(-1). Add parens around negative numbers to avoid this
-- problem.
-- Here are some other list functions:
head :: [a] -> a -- returns the first element in a list (same as car in lisp)
head (x:xs) = x
tail :: [a] -> [a] -- removes the first element from a list (same as cdr)
tail (x:xs) = xs
null :: [a] -> Bool
null [] = True
null (x:xs) = False
cons :: a -> [a] -> [a]
cons x xs = x:xs
nil :: [a]
nil = []
-- Length could be defined using these functions too. This is
-- not good Haskell style but does illustrate these other list functions.
-- The if - then - else will be discussed later. Haskell programmers feel
-- that the pattern matching style, as used in the previous version of
-- length, is more natural and readable.
length' :: [a] -> Int -- Note that ' can be part of a name
length' x = if null x then 0 else 1 + length' (tail x)
-- A test case for length', cons, and nil
e1 = length' (cons 1 (cons 2 nil))
-- We haven't said anything about errors yet. Each of the following
-- examples illustrates a potential runtime or compile time error. The
-- compile time error is commented out so that other examples will compile;
-- you can uncomment them and see what happens.
-- e2 = cons True False -- Why is this not possible in Haskell?
e3 = tail (tail ['a']) -- What happens if you evaluate this?
e4 = [] -- This is especially mysterious!
-- This last example, e4, is something hard to explain but is often
-- encountered early by novices. We haven't explained yet how the system
-- prints out the expressions you type in - this will wait until later.
-- However, the problem here is that e4 has the type [a]. The printer for
-- the list datatype is complaining that it needs to know a specific type
-- for the list elements even though the list has no elements! This can
-- be avoided by giving e4 a type such as [Int]. (To further confuse you,
-- try giving e4 the type [Char] and see what happens.)
-- Page 3 Section 2.2
-- Section 2.2 User-Defined Types
module Test(Bool) where
-- The type Bool is already defined in the Prelude so there is no
-- need to define it here.
data Color = Red | Green | Blue | Indigo | Violet deriving Text
-- The `deriving Text' is necessary if you want to print a Color value.
-- You can now evaluate these expressions.
e1 :: Color
e1 = Red
e2 :: [Color]
e2 = [Red,Blue]
-- It is very important to keep the expression language and the type
-- language in Haskell separated. The data declaration above defines
-- the type constructor Color. This is a nullary constructor: it takes no
-- arguments. Color is found ONLY in the type language - it can not be
-- part of an expression. e1 = Color is meaningless. (Actually, Color could
-- be both a data constructor and a type constructor but we'll ignore this
-- possibility for now). On the other hand, Red, Blue, and so on are
-- (nullary) data constructors. They can appear in expressions and
-- in patterns (described later). The declaration e1 :: Blue would also
-- be meaningless. Data constructors can be defined ONLY in a data
-- declaration.
-- In the next example, Point is a type constructor and Pt is a data
-- constructor. Point takes one argument and Pt takes two. A data constructor
-- like Pt is really just an ordinary function except that it can be used in
-- a pattern. Type signatures can not be supplied directly for data
-- constructors; their typing is completely defined by the data declaration.
-- However, data constructors have a signature just like any variable:
-- Pt :: a -> a -> Point a -- Not valid Haskell syntax
-- That is, Pt is a function which takes two arguments with the same
-- arbitrary type and returns a value containing the two argument values.
data Point a = Pt a a deriving Text
e3 :: Point Float
e3 = Pt 2.0 3.0
e4 :: Point Char
e4 = Pt 'a' 'b'
e5 :: Point (Point Int)
e5 = Pt (Pt 1 2) (Pt 3 4)
-- e6 = Pt 'a' True -- This is a typing error
-- The individual components of a point do not have names.
-- Let's jump ahead a little so that we can write functions using these
-- data types. Data constructors (Red, Blue, ..., and Pt) can be used in
-- patterns. When more than one equation is used to define a function,
-- pattern matching occurs top down.
-- A function to remove red from a list of colors.
removeRed :: [Color] -> [Color]
removeRed [] = []
removeRed (Red:cs) = removeRed cs
removeRed (c:cs) = c : removeRed cs -- c cannot be Red at this point
e7 :: [Color]
e7 = removeRed [Blue,Red,Green,Red]
-- Pattern matching is capable of testing equality with a specific color.
-- All equations defining a function must share a common type. A
-- definition such as:
-- foo Red = 1
-- foo (Pt x y) = x
-- would result in a type error since the argument to foo cannot be both a
-- Color and a Point. Similarly, the right hand sides must also share a
-- common type; a definition such as
-- foo Red = Blue
-- foo Blue = Pt Red Red
-- would also result in a type error.
-- Here's a couple of functions defined on points.
dist :: Point Float -> Point Float -> Float
dist (Pt x1 y1) (Pt x2 y2) = sqrt ((x1-x2)^2 + (y1-y2)^2)
midpoint :: Point Float -> Point Float -> Point Float
midpoint (Pt x1 y1) (Pt x2 y2) = Pt ((x1+x2)/2) ((y1+y2)/2)
p1 :: Point Float
p1 = Pt 1.0 1.0
p2 :: Point Float
p2 = Pt 2.0 2.0
e8 :: Float
e8 = dist p1 p2
e9 :: Point Float
e9 = midpoint p1 p2
-- The only way to take apart a point is to pattern match.
-- That is, the two values which constitute a point must be extracted
-- by matching a pattern containing the Pt data constructor. Much
-- more will be said about pattern matching later.
-- Haskell prints values in the same syntax used in expressions. Thus
-- Pt 1 2 would print as Pt 1 2 (of course, Pt 1 (1+1) would also print
-- as Pt 1 2).
-- Page 4 Section 2.3
-- Section 2.3 Recursive Types
module Test where
data Tree a = Leaf a | Branch (Tree a) (Tree a) deriving Text
-- The following typings are implied by this declaration. As before,
-- this is not valid Haskell syntax.
-- Leaf :: a -> Tree a
-- Branch :: Tree a -> Tree a -> Tree a
fringe :: Tree a -> [a]
fringe (Leaf x) = [x]
fringe (Branch left right) = fringe left ++ fringe right
-- The following trees can be used to test functions:
tree1 :: Tree Int
tree1 = Branch (Leaf 1) (Branch (Branch (Leaf 2) (Leaf 3)) (Leaf 4))
tree2 :: Tree Int
tree2 = Branch (Branch (Leaf 3) (Leaf 1)) (Branch (Leaf 4) (Leaf 1))
tree3 :: Tree Int
tree3 = Branch tree1 tree2
-- Try evaluating `fringe tree1' and others.
-- Here's another tree function:
twist :: Tree a -> Tree a
twist (Branch left right) = Branch right left
twist x = x -- This equation only applies to leaves
-- Here's a function which compares two trees to see if they have the
-- same shape. Note the signature: the two trees need not contain the
-- same type of values.
sameShape :: Tree a -> Tree b -> Bool
sameShape (Leaf x) (Leaf y) = True
sameShape (Branch l1 r1) (Branch l2 r2) = sameShape l1 l2 && sameShape r1 r2
sameShape x y = False -- One is a branch, the other is a leaf
-- The && function is a boolean AND function.
-- The entire pattern on the left hand side must match in order for the
-- right hand side to be evaluated. The first clause requires both
-- arguments to be a leaf' otherwise the next equation is tested.
-- The last clause will always match: the final x and y match both
-- leaves and branches.
-- This compares a tree of integers to a tree of booleans.
e1 = sameShape tree1 (Branch (Leaf True) (Leaf False))
-- Page 5 Sections 2.4, 2.5, 2.6
-- Section 2.4 Type Synonyms
module Test(Bool) where
-- Since type synonyms are part of the type language only, it's hard to
-- write a program which shows what they do. Essentially, they are like
-- macros for the type language. They can be used interchangably with their
-- definition:
e1 :: String
e1 = "abc"
e2 :: [Char] -- No different than String
e2 = e1
-- In the written tutorial the declaration of `Addr' is a data type
-- declaration, not a synonym declaration. This shows that the data
-- type declaration as well as a signature can reference a synonym.
-- Section 2.5 Built-in Types
-- Tuples are an easy way of grouping a set of data values. Here are
-- a few tuples. Note the consistancy in notation between the values and
-- types.
e3 :: (Bool,Int)
e3 = (True,4)
e4 :: (Char,[Int],Char)
e4 = ('a',[1,2,3],'b')
-- Here's a function which returns the second component of a 3 tuple.
second :: (a,b,c) -> b
second (a,b,c) = b
-- Try out `second e3' and `second e4' - what happens?
-- Each different size of tuple is a completely distinct type. There is
-- no general way to append two arbitrary tuples or randomly select the
-- i'th component of an arbitrary tuple. Here's a function built using
-- 2-tuples to represent intervals.
-- Use a type synonym to represent homogenous 2 tuples
type Interval a = (a,a)
containsInterval :: Interval Int -> Interval Int -> Bool
containsInterval (xmin,xmax) (ymin,ymax) = xmin <= ymin && xmax >= ymax
p1 :: Interval Int
p1 = (2,3)
p2 :: Interval Int
p2 = (1,4)
e5 = containsInterval p1 p2
e6 = containsInterval p2 p1
-- Here's a type declaration for a type isomorphic to lists:
data List a = Nil | Cons a (List a) deriving Text
-- Except for the notation, this is completely equivalent to ordinary lists
-- in Haskell.
length' :: List a -> Int
length' Nil = 0
length' (Cons x y) = 1 + length' y
e7 = length' (Cons 'a' (Cons 'b' (Cons 'c' Nil)))
-- It's hard to demonstrate much about the `non-specialness' of built-in
-- types. However, here is a brief summary:
-- Numbers and characters, such as 1, 2.2, or 'a', are the same as nullary
-- type constructors.
-- Lists have a special type constructor, [a] instead of List a, and
-- an odd looking data constructor, []. The other data constructor, :, is
-- not `unusual', syntactically speaking. The notation [x,y] is just
-- syntax for x:y:[] and "abc" for 'a' : 'b' : 'c' : [].
-- Tuples use a special syntax. In a type expression, a 2 tuple containing
-- types a and be would be written (a,b) instead of using a prefix type
-- constructor such as Tuple2 a b. This same notation is used to build
-- tuple values: (1,2) would construct a 2 tuple containing the values 1 and 2.
-- Page 6 Sections 2.5.1, 2.5.2
module Test(Bool) where
-- Section 2.5.1 List Comprehensions and Arithmetic Sequences
-- Warning: brackets in Haskell are used in three different types
-- of expressions: lists, as in [a,b,c], sequences (distinguished by
-- the ..), as in [1..2], and list comprehensions (distinguished by the
-- bar: |), as in [x+1 | x <- xs, x > 1].
-- Before list comprehensions, let's start out with sequences:
e1 :: [Int]
e1 = [1..10] -- Step is 1
e2 :: [Int]
e2 = [1,3..10] -- Step is 3 - 1
e3 :: [Int]
e3 = [1,-1..-10]
e4 :: [Char]
e4 = ['a'..'z'] -- This works on chars too
-- We'll avoid infinite sequences like [1..] for now. If you print one,
-- use C-c i to interrupt the Haskell program.
-- List comprehensions are very similar to nested loops. They return a
-- list of values generated by the expression inside the loop. The filter
-- expressions are similar to conditionals in the loop.
-- This function does nothing at all! It just scans through a list and
-- copies it into a new one.
doNothing :: [a] -> [a]
doNothing l = [x | x <- l]
-- Adding a filter to the previous function allows only selected elements to
-- be generated. This is similar to what is done in quicksort.
positives :: [Int] -> [Int]
positives l = [x | x <- l, x > 0]
e5 = positives [2,-4,5,6,-5,3]
-- Now the full quicksort function.
quicksort :: [Char] -> [Char] -- Use Char just to be different!
quicksort [] = []
quicksort (x:xs) = quicksort [y | y <- xs, y <= x] ++
[x] ++
quicksort [y | y <- xs, y > x]
e6 = quicksort "Why use Haskell?"
-- Now for some nested loops. Each generator, <-, adds another level of
-- nesting to the loop. Note that the variable introduced by each generator
-- can be used in each following generator; all variables can be used in the
-- generated expression:
e7 :: [(Int,Int)]
e7 = [(x,y) | x <- [1..5], y <- [x..5]]
-- Now let's add some guards: (the /= function is `not equal')
e8 :: [(Int,Int)]
e8 = [(x,y) | x <- [1..7], x /= 5, y <- [x..8] , x*y /= 12]
-- This is the same as the loop: (going to a psuedo Algol notation)
-- for x := 1 to 7 do
-- if x <> 5 then
-- for y := x to 8 do
-- if x*y <> 12
-- generate (x,y)
-- Section 2.5.2 Strings
e9 = "hello" ++ " world"
-- Page 7 Sections 3, 3.1
module Test(Bool) where
import Prelude hiding (map)
-- Section 3 Functions
add :: Int -> Int -> Int
add x y = x+y
e1 :: Int
e1 = add 1 2
-- This Int -> Int is the latter part of the signature of add:
-- add :: Int -> (Int -> Int)
succ :: Int -> Int
succ = add 1
e2 :: Int
e2 = succ 3
map :: (a->b) -> [a] -> [b]
map f [] = []
map f (x:xs) = f x : (map f xs)
e3 :: [Int]
e3 = map (add 1) [1,2,3]
-- This next definition is the equivalent to e3
e4 :: [Int]
e4 = map succ [1,2,3]
-- Heres a more complex example. Define flist to be a list of functions:
flist :: [Int -> Int]
flist = map add [1,2,3]
-- This returns a list of functions which add 1, 2, or 3 to their input.
-- Warning: Haskell should print flist as something like
-- [<<function>>,<<function>>,<<function>>]
-- Now, define a function which takes a function and returns its value
-- when applied to the constant 1:
applyTo1 :: (Int -> a) -> a
applyTo1 f = f 1
e5 :: [Int]
e5 = map applyTo1 flist -- Apply each function in flist to 1
-- If you want to look at how the type inference works, figure out how
-- the signatures of map, applyTo1, and flist combine to yield [Int].
-- Section 3.1 Lambda Abstractions
-- The symbol \ is like `lambda' in lisp or scheme.
-- Anonymous functions are written as \ arg1 arg2 ... argn -> body
-- Instead of naming every function, you can code it inline with this
-- notation:
e6 = map (\f -> f 1) flist
-- Be careful with the syntax here. \x->\y->x+y parses as
-- \ x ->\ y -> x + y. The ->\ is all one token. Use spaces!!
-- This is identical to e5 except that the applyTo1 function has no name.
-- Function arguments on the left of an = are the same as lambda on the
-- right:
add' = \x y -> x+y -- identical to add
succ' = \x -> x+1 -- identical to succ
-- As with ordinary function, the parameters to anonymous functions
-- can be patterns:
e7 :: [Int]
e7 = map (\(x,y) -> x+y) [(1,2),(3,4),(5,6)]
-- Functions defined by more than one equation, like map, cannot
-- be converted to anonymous lambda functions quite as easily - a case
-- statement is also required. This is discussed later.
-- Page 8 Sections 3.2, 3.2.1, 3.2.2
module Test(Bool) where
import Prelude hiding ((++),(.))
-- Section 3.2 Infix operators
-- Haskell has both identifiers, like x, and operators, like +.
-- These are just two different types of syntax for variables.
-- However, operators are by default used in infix notation.
-- Briefly, identifiers begin with a letter and may have numbers, _, and '
-- in them: x, xyz123, x'', xYz'_12a. The case of the first letter
-- distinguishes variables from data constructors (or type variables from
-- type constructors). An operator is a string of symbols, where
-- :!#$%&*+./<=>?@\^| are all symbols. If the first character is : then
-- the operator is a data constructor; otherwise it is an ordinary
-- variable operator. The - and ~ characters may start a symbol but cannot
-- be used after the first character. This allows a*-b to parse as
-- a * - b instead of a *- b.
-- Operators can be converted to identifiers by enclosing them in parens.
-- This is required in signature declarations. Operators can be defined
-- as well as used in the infix style:
(++) :: [a] -> [a] -> [a]
[] ++ y = y
(x:xs) ++ y = x : (xs ++ y)
-- Table 2 (Page 54) of the report is invaluable for sorting out the
-- precedences of the many predefined infix operators.
e1 = "Foo" ++ "Bar"
-- This is the same function without operator syntax
appendList :: [a] -> [a] -> [a]
appendList [] y = y
appendList (x:xs) y = x : appendList xs y
(.) :: (b -> c) -> (a -> b) -> (a -> c)
f . g = \x -> f (g x)
add1 :: Int -> Int
add1 x = x+1
e2 = (add1 . add1) 3
-- Section 3.2.1 Sections
-- Sections are a way of creating unary functions from infix binary
-- functions. When a parenthesized expression starts or ends in an
-- operator, it is a section. Another definition of add1:
add1' :: Int -> Int
add1' = (+ 1)
e3 = add1' 4
-- Here are a few section examples:
e4 = map (++ "abc") ["x","y","z"]
e5 = map ("abc" ++) ["x","y","z"]
-- Section 3.2.2 Fixity Declarations
-- We'll avoid any demonstration of fixity declarations. The Prelude
-- contains numerous examples.
-- Page 9 Sections 3.3, 3.4, 3.5
module Test(Bool) where
import Prelude hiding (take,zip)
-- Section 3.3 Functions are Non-strict
-- Observing lazy evaluation can present difficulties. The essential
-- question is `does an expression get evaluated?'. While in theory using a
-- non-terminating computation is the way evaluation issues are examined,
-- we need a more practical approach. The `error' function serves as
-- a bottom value. Evaluating this function prints an error message and
-- halts execution.
bot = error "Evaluating Bottom"
e1 :: Bool -- This can be any type at all!
e1 = bot -- evaluate this and see what happens.
const1 :: a -> Int
const1 x = 1
e2 :: Int
e2 = const1 bot -- The bottom is not needed and will thus not be evaluated.
-- Section 3.4 "Infinite" Data Structures
-- Data structures are constructed lazily. A constructor like : will not
-- evaluate its arguments until they are demanded. All demands arise from
-- the need to print the result of the computation -- components not needed
-- to compute the printed result will not be evaluated.
list1 :: [Int]
list1 = (1:bot)
e3 = head list1 -- doesnt evaluate bot
e4 = tail list1 -- does evaluate bot
-- Some infinite data structures. Don't print these! If you do, you will
-- need to interrupt the system (C-c i) or kill the Haskell process.
ones :: [Int]
ones = 1 : ones
numsFrom :: Int -> [Int]
numsFrom n = n : numsFrom (n+1)
-- An alternate numsFrom using series notation:
numsFrom' :: Int -> [Int]
numsFrom' n = [n..]
squares :: [Int]
squares = map (^2) (numsFrom 0)
-- Before we start printing anything, we need a function to truncate these
-- infinite lists down to a more manageable size. The `take' function
-- extracts the first k elements of a list:
take :: Int -> [a] -> [a]
take 0 x = [] -- two base cases: k = 0
take k [] = [] -- or the list is empty
take k (x:xs) = x : take (k-1) xs
-- now some printable lists:
e5 :: [Int]
e5 = take 5 ones
e6 :: [Int]
e6 = take 5 (numsFrom 10)
e7 :: [Int]
e7 = take 5 (numsFrom' 0)
e8 :: [Int]
e8 = take 5 squares
-- zip is a function which turns two lists into a list of 2 tuples. If
-- the lists are of differing sizes, the result is as long as the
-- shortest list.
zip (x:xs) (y:ys) = (x,y) : zip xs ys
zip xs ys = [] -- one of the lists is []
e9 :: [(Int,Int)]
e9 = zip [1,2,3] [4,5,6]
e10 :: [(Int,Int)]
e10 = zip [1,2,3] ones
fib :: [Int]
fib = 1 : 1 : [x+y | (x,y) <- zip fib (tail fib)]
e11 = take 5 fib
-- Let's do this without the list comprehension:
fib' :: [Int]
fib' = 1 : 1 : map (\(x,y) -> x+y) (zip fib (tail fib))
-- This could be written even more cleanly using a map function which
-- maps a binary function over two lists at once. This is in the
-- Prelude and is called zipWith.
fib'' :: [Int]
fib'' = 1 : 1 : zipWith (+) fib (tail fib)
-- For more examples using infinite structures look in the demo files
-- that come with Yale Haskell. Both the pascal program and the
-- primes program use infinite lists.
-- Section 3.5 The Error Function
-- Too late - we already used it!
-- Page 10 Sections 4, 4.1, 4.2
module Test(Bool) where
import Prelude hiding (take,(^))
-- Section 4 Case Expressions and Pattern Matching
-- Now for details of pattern matching. We use [Int] instead of [a]
-- since the only value of type [a] is [].
contrived :: ([Int], Char, (Int, Float), String, Bool) -> Bool
contrived ([], 'b', (1, 2.0), "hi", True) = False
contrived x = True -- add a second equation to avoid runtime errors
e1 :: Bool
e1 = contrived ([], 'b', (1, 2.0), "hi", True)
e2 :: Bool
e2 = contrived ([1], 'b', (1, 2.0), "hi", True)
-- Contrived just tests its input against a big constant.
-- Linearity in pattern matching implies that patterns can only compare
-- values with constants. The following is not valid Haskell:
-- member x [] = False
-- member x (x:ys) = True -- Invalid since x appears twice
-- member x (y:ys) = member x ys
f :: [a] -> [a]
f s@(x:xs) = x:s
f _ = []
e3 = f "abc"
-- Another use of _:
middle :: (a,b,c) -> b
middle (_,x,_) = x
e4 :: Char
e4 = middle (True, 'a', "123")
(^) :: Int -> Int -> Int
x ^ 0 = 1
x ^ (n+1) = x*(x^n)
e5 :: Int
e5 = 3^3
e6 :: Int
e6 = 4^(-2) -- Notice the behavior of the + pattern on this one
-- Section 4.1 Pattern Matching Semantics
-- Here's an extended example to illustrate the left -> right, top -> bottom