-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlec-monads.lhs
1902 lines (1338 loc) · 45.3 KB
/
lec-monads.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
---
title: Programming With Effects
---
<div class="hidden">
\begin{code}
{-@ LIQUID "--no-termination" @-}
module Monads () where
import Data.Map hiding (map)
\end{code}
</div>
**Formatted version of the lecture notes by [Graham Hutton][0], January 2011**
Shall we be pure or impure?
---------------------------
The functional programming community divides into two camps:
- "Pure" languages, such as Haskell, are based directly
upon the mathematical notion of a function as a
mapping from arguments to results.
- "Impure" languages, such as ML, are based upon the
extension of this notion with a range of possible
effects, such as exceptions and assignments.
Pure languages are easier to reason about and may benefit
from lazy evaluation, while impure languages may be more
efficient and can lead to shorter programs.
One of the primary developments in the programming language
community in recent years (starting in the early 1990s) has
been an approach to integrating the pure and impure camps,
based upon the notion of a "monad". This note introduces
the use of monads for programming with effects in Haskell.
Abstracting programming patterns
================================
Monads are an example of the idea of abstracting out a common
programming pattern as a definition. Before considering monads,
let us review this idea, by means of two simple functions:
~~~~~{.haskell}
inc :: [Int] -> [Int]
inc [] = []
inc (n:ns) = n+1 : inc ns
sqr :: [Int] -> [Int]
sqr [] = []
sqr (n:ns) = n^2 : sqr ns
~~~~~
Both functions are defined using the same programming pattern,
namely mapping the empty list to itself, and a non-empty list
to some function applied to the head of the list and the result
of recursively processing the tail of the list in the same manner.
Abstracting this pattern gives the library function called `map`
~~~~~{.haskell}
map :: (a -> b) -> [a] -> [b]
map f [] = []
map f (x:xs) = f x : map f xs
~~~~~
using which our two examples can now be defined more compactly:
\begin{code}
inc = map (+1)
sqr = map (^2)
\end{code}
Quiz
----
What is the type of `foo` defined as:
~~~~~{.haskell}
data Maybe a = Just a | Nothing
foo f z = case z of
Just x -> Just (f x)
Nothing -> Nothing
~~~~~
a. `Maybe a`
b. `(a -> b) -> Maybe a -> Maybe b`
c. `(a -> b) -> a -> Maybe b`
d. `(a -> b) -> Maybe a -> b`
e. `(a -> Maybe b) -> Maybe a -> Maybe b`
~~~~~{.haskell}
~~~~~
Generalizing `map`
------------------
The same notion of `map`ping applies to other types, for example, you can
imagine:
~~~~~{.haskell}
map :: (a -> b) -> Maybe a -> Maybe b
~~~~~
or
~~~~~{.haskell}
map :: (a -> b) -> Tree a -> Tree b
~~~~~
or
~~~~~{.haskell}
map :: (a -> b) -> IO a -> IO b
~~~~~
Quiz
----
Which of the following is a valid
`iomap :: (a -> b) -> IO a -> IO b`
~~~~~{.haskell}
iomap f x = f x -- a
iomap f x = do f x -- b
iomap f x = do y <- f x -- c
return y
iomap f x = do y <- x -- d
return (f y)
iomap f x = do y <- x -- e
f y
~~~~~
For this reason, there is a *typeclass* called `Functor` that
corresponds to the type constructors that you can `map` over:
~~~~~{.haskell}
class Functor m where
fmap :: (a -> b) -> m a -> m b
~~~~~
**Note: ** The `m` is the type constructor, e.g. `[]` or `IO` or `Maybe`
We can make `[]` or `IO` or `Maybe` be **instances** of `Functor` by:
~~~~~{.haskell}
instance Functor [] where
fmap f [] = []
fmap f (x:xs) = f x : fmap f xs
~~~~~
and
~~~~~{.haskell}
instance Functor Maybe where
fmap f Nothing = Nothing
fmap f (Just x) = Just (f x)
~~~~~
and
~~~~~{.haskell}
instance Functor IO where
fmap f x = do {y <- x; return (f x)}
~~~~~
foo = fmap (+1)
baz = foo Nothing
what is the value of `baz`?
A. Nothing
B. Just 1
C. Just 2
D. Type ERROR.
E. None of the above
Generalizing `map` to Many Arguments
------------------------------------
We can generalize `map` to many arguments.
With *one* argument, we call it `lift1`
~~~~~{.haskell}
lift1 :: (a -> b) -> [a] -> [b]
lift1 f [] = []
lift1 f (x:xs) = f x : lift1 f xs
~~~~~
You can imagine defining a version for *two* arguments
~~~~~{.haskell}
lift2 :: (a1 -> a2 -> b) -> [a1] -> [a2] -> [b]
lift2 f (x:xs) (y:ys) = f x y : lift2 f xs ys
lift2 f _ _ = []
~~~~~
and *three* arguments and so on
~~~~~{.haskell}
lift3 :: (a1 -> a2 -> a3 -> b) -> [a1] -> [a2] -> [a3] -> [b]
~~~~~
or
~~~~~{.haskell}
lift2 :: (a1 -> a2 -> b) -> Maybe a1 -> Maybe a2 -> Maybe b
lift2 f (Just x) (Just y) = Just (f x y)
lift2 _ _ _ = Nothing
lift3 :: (a1 -> a2 -> a3 -> b)
-> Maybe a1
-> Maybe a2
-> Maybe a3
-> Maybe b
~~~~~
or
~~~~~{.haskell}
lift2 :: (a1 -> a2 -> b) -> IO a1 -> IO a2 -> IO b
lift2 f x1 x2 = do a1 <- x1
a2 <- x2
return (f a1 a2)
lift3 :: (a1 -> a2 -> a3 -> b)
-> IO a1
-> IO a2
-> IO a3
-> IO b
~~~~~
For this reason, there is a *typeclass* called `Applicative` that
corresponds to the type constructors that you can `lift2` or `lift3`
over.
~~~~~{.haskell}
liftA :: Applicative t => (a -> b) -> t a -> t b
liftA2 :: Applicative t => (a1 -> a2 -> b) -> t a1 -> t a2 -> t b
liftA3 :: Applicative t
=> (a1 -> a2 -> a3 -> b)
-> t a1
-> t a2
-> t a3
-> t b
~~~~~
**Note:** The `t` is the type constructor, e.g. `[]` or `IO` or `Maybe` or `Behavior`.
A Simple Evaluator
==================
Consider the following simple language of expressions that are
built up from integer values using a division operator:
\begin{code}
data Expr1 = Val1 Int
| Div1 Expr1 Expr1
deriving (Show)
\end{code}
Such expressions can be evaluated as follows:
\begin{code}
eval1 :: Expr1 -> Int
eval1 (Val1 n) = n
eval1 (Div1 x y) = eval1 x `div` eval1 y
\end{code}
However, this function doesn't take account of the possibility
of **division by zero**, and will produce an error in this case.
In order to deal with this explicitly, we can use the `Maybe` type
~~~~~{.haskell}
data Maybe a = Nothing | Just a
~~~~~
to define a *safe* version of division
\begin{code}
safediv :: Int -> Int -> Maybe Int
safediv n m = if m == 0 then Nothing else Just (n `div` m)
\end{code}
and then modify our evaluator as follows:
~~~~~{.haskell}
eval1' :: Expr1 -> Maybe Int
eval1' (Val1 n) = Just n
eval1' (Div1 x y) = case eval1' x of
Nothing -> Nothing
Just n1 -> case eval1' y of
Nothing -> Nothing
Just n2 -> n1 `safeDiv` n2
~~~~~
As in the previous section, we can observe a common pattern, namely
performing a case analysis on a value of a `Maybe` type, mapping `Nothing`
to itself, and `Just x` to some result depending upon `x`. (*Aside*: we
could go further and also take account of the fact that the case analysis
is performed on the result of an eval, but this would lead to the more
advanced notion of a monadic fold.)
How should this pattern be abstracted out? One approach would be
to observe that a key notion in the evaluation of division is the
sequencing of two values of a `Maybe` type, namely the results of
evaluating the two arguments of the division. Based upon this
observation, we could define a sequencing function
\begin{code}
seqn :: Maybe a -> Maybe b -> Maybe (a, b)
seqn Nothing _ = Nothing
seqn _ Nothing = Nothing
seqn (Just x) (Just y) = Just (x, y)
\end{code}
using which our evaluator can now be defined more compactly:
~~~~~{.haskell}
eval :: Expr1 -> Maybe Int
eval (Val n) = Just n
eval (Div x y) = apply f (eval x `seqn` eval y)
where f (n, m) = safediv n m
~~~~~
Quiz
----
What must the type of `apply` be for the above to typecheck?
a. `((Int, Int) -> Maybe Int) -> Maybe (Int, Int) -> Maybe Int`
b. `(a -> Maybe b) -> Maybe a -> Maybe b`
c. `((Int, Int) -> Int) -> (Int, Int) -> Int`
d. `(a -> b) -> a -> b`
e. `(a -> b) -> Maybe a -> Maybe b`
~~~~~{.haskell}
~~~~~
The auxiliary function `apply` is an analogue of application
for `Maybe`, and is used to process the results of the two
evaluations:
~~~~~{.haskell}
apply :: (a -> Maybe b) -> Maybe a -> Maybe b
apply f Nothing = Nothing
apply f (Just x) = f x
~~~~~
In practice, however, using `seqn` can lead to programs that manipulate
nested tuples, which can be messy. For example, the evaluation of
an operator `Op` with three arguments may be defined by:
~~~~~{.haskell}
eval (Op x y z) = map f (eval x `seqn` (eval y `seqn` eval z))
where f (a, (b, c)) = ...
~~~~~
Combining Sequencing and Processing
-----------------------------------
The problem of nested tuples can be avoided by returning to our
original observation of a common pattern:
"performing a case analysis on a value of a `Maybe` type,
mapping `Nothing` to itself, and
`Just x`to some result depending upon `x`".
Abstract this pattern directly gives a new *sequencing* operator
that we write as `>>=`, and read as "then":
~~~~~{.haskell}
(>>=) :: Maybe a -> (a -> Maybe b) -> Maybe b
m >>= f = case m of
Nothing -> Nothing
Just x -> f x
~~~~~
Replacing the use of case analysis by pattern matching gives a
more compact definition for this operator:
~~~~~{.haskell}
(>>=) :: Maybe a -> (a -> Maybe b) -> Maybe b
Nothing >>= _ = Nothing
(Just x) >>= f = f x
~~~~~
That is, if the first argument is `Nothing` then the second argument
is ignored and `Nothing` is returned as the result. Otherwise, if
the first argument is of the form `Just x`, then the second argument
is applied to `x` to give a result of type `Maybe b`.
The `>>=` operator avoids the problem of nested tuples of results
because the result of the first argument is made directly available
for processing by the second, rather than being paired up with the
second result to be processed later on. In this manner, `>>=` integrates
the sequencing of values of type `Maybe` with the processing of their
result values. In the literature, `>>=` is often called *bind*, because
the second argument binds the result of the first.
Using `>>=`, our evaluator can now be rewritten as:
~~~~~{.haskell}
eval (Val n) = Just n
eval (Div x y) = eval x >>= (\n ->
eval y >>= (\m ->
safediv n m
)
)
~~~~~
The case for division can be read as follows: evaluate `x` and call
its result value `n`, then evaluate `y` and call its result value `m`,
and finally combine the two results by applying `safediv`. In
fact, the scoping rules for lambda expressions mean that the
parentheses in the case for division can freely be omitted.
Generalising from this example, a typical expression built using
the `>>=` operator has the following structure:
~~~~~{.haskell}
m1 >>= \x1 ->
m2 >>= \x2 ->
...
mn >>= \xn ->
f x1 x2 ... xn
~~~~~
That is, evaluate each of the expression `m1`, `m2`,...,`mn` in turn,
and combine their result values `x1`, `x2`,..., `xn` by applying the
function f. The definition of `>>=` ensures that such an expression
only succeeds (returns a value built using `Just`) if each `mi` in
the sequence succeeds.
In other words, the programmer does not have to worry about dealing
with the possible failure (returning `Nothing`) of any of the component
expressions, as this is handled automatically by the `>>=` operator.
Haskell provides a special notation for expressions of the above
structure, allowing them to be written in a more appealing form:
~~~~~{.haskell}
do x1 <- m1
x2 <- m2
...
xn <- mn
f x1 x2 ... xn
~~~~~
Hence, for example, our evaluator can be redefined as:
~~~~~{.haskell}
eval (Val n) = Just n
eval (Div x y) = do n <- eval x
m <- eval y
safediv n m
~~~~~
Exercise
--------
- Show that the version of `eval` defined using `>>=` is equivalent to
our original version, by expanding the definition of `>>=`.
- Redefine `seqn x y` and `eval (Op x y z)` using the `do` notation.
Monads in Haskell
=================
The `do` notation for sequencing is not specific to the `Maybe` type,
but can be used with any type that forms a *monad*. The general
concept comes from a branch of mathematics called category theory.
In Haskell, however, a monad is simply a parameterised type `m`,
together with two functions of the following types:
~~~~~{.haskell}
(>>=) :: m a -> (a -> m b) -> m b
return :: a -> m a
~~~~~
(*Aside*: the two functions are also required to satisfy some simple
properties, but we will return to these later.) For example, if
we take `m` as the parameterised type `Maybe`, `return` as the function
`Just :: a -> Maybe a`, and `>>=` as defined in the previous section,
then we obtain our first example, called the *maybe monad*.
In fact, we can capture the notion of a monad as a new class
declaration. In Haskell, a class is a collection of types that
support certain overloaded functions. For example, the class
`Eq` of equality types can be declared as follows:
~~~~~{.haskell}
class Eq a where
(==) :: a -> a -> Bool
(/=) :: a -> a -> Bool
x /= y = not (x == y)
~~~~~
The declaration states that for a type `a` to be an instance of
the class `Eq`, it must support equality and inequality operators
of the specified types. In fact, because a default definition
has already been included for `/=`, declaring an instance of this
class only requires a definition for `==`. For example, the type
`Bool` can be made into an equality type as follows:
~~~~~{.haskell}
instance Eq Bool where
False == False = True
True == True = True
_ == _ = False
~~~~~
The notion of a monad can now be captured as follows:
~~~~~{.haskell}
class Monad m where
return :: a -> m a
(>>=) :: m a -> (a -> m b) -> m b
~~~~~
That is, a monad is a parameterised type `m` that supports `return`
and `>>=` functions of the specified types. The fact that `m` must
be a parameterised type, rather than just a type, is inferred from its
use in the types for the two functions. Using this declaration,
it is now straightforward to make `Maybe` into a monadic type:
~~~~~{.haskell}
instance Monad Maybe where
-- return :: a -> Maybe a
return x = Just x
-- (>>=) :: Maybe a -> (a -> Maybe b) -> Maybe b
Nothing >>= _ = Nothing
(Just x) >>= f = f x
~~~~~
(*Aside*: types are not permitted in instance declarations, but we
include them as comments for reference.) It is because of this
declaration that the `do` notation can be used to sequence `Maybe`
values. More generally, Haskell supports the use of this notation
with any monadic type. In the next few sections we give some
further examples of types that are monadic, and the benefits
that result from recognising and exploiting this fact.
The List Monad
--------------
The maybe monad provides a simple model of computations that can
fail, in the sense that a value of type `Maybe a` is either `Nothing`,
which we can think of as representing failure, or has the form
`Just x` for some `x` of type `a`, which we can think of as success.
The list monad generalises this notion, by permitting multiple
results in the case of success. More precisely, a value of
`[a]` is either the empty list `[]`, which we can think of as
failure, or has the form of a non-empty list `[x1,x2,...,xn]`
for some `xi` of type `a`, which we can think of as success.
Quiz
----
Lets make lists an instance of `Monad` by:
~~~~~{.haskell}
class Monad m where
return :: a -> m a
(>>=) :: m a -> (a -> m b) -> m b
instance Monad [] where
return = returnForList
(>>=) = bindForList
~~~~~
What must the type of `returnForList` be ?
a. `[a]`
b. `a -> a`
c. `a -> [a]`
d. `[a] -> a`
e. `[a] -> [a]`
Quiz
----
Lets make lists an instance of `Monad` by:
~~~~~{.haskell}
class Monad m where
return :: a -> m a
(>>=) :: m a -> (a -> m b) -> m b
instance Monad [] where
return = returnForList
(>>=) = bindForList
~~~~~
What must the type of `bindForList` be?
a. `[a] -> [b] -> [b]`
b. `[a] -> (a -> b) -> [b]`
c. `[a] -> (a -> [b]) -> b`
d. `[a] -> (a -> [b]) -> [b]`
e. `[a] -> [b]`
~~~~~{.haskell}
~~~~~
Quiz
----
Which of the following is a valid
`bindForList :: [a] -> (a -> [b]) -> [b]`?
~~~~~{.haskell}
-- a
bfl f [] = []
bfl f (x:xs) = f x : bfl f xs
-- b
bfl f [] = []
bfl f (x:xs) = f x ++ bfl f xs
-- c
bfl [] f = []
bfl (x:xs) f = f x ++ bfl f xs
-- d
bfl [] f = []
bfl (x:xs) f = f x : bfl f xs
-- e
bfl [] f = []
bfl (x:xs) f = x : f xs
~~~~~
Making lists into a monadic type is straightforward:
~~~~~{.haskell}
instance Monad [] where
-- return :: a -> [a]
return x = [x]
-- (>>=) :: [a] -> (a -> [b]) -> [b]
[] >>= f = []
(x:xs) >>= f = f x ++ (xs >>= f)
~~~~~
(*Aside*: in this context, `[]` denotes the list type `[a]` without
its parameter.) That is, return simply converts a value into a
successful result containing that value, while `>>=` provides a
means of sequencing computations that may produce multiple
results: `xs >>= f` applies the function f to each of the results
in the list xs to give a nested list of results, which is then
concatenated to give a single list of results.
As a simple example of the use of the list monad, a function
that returns all possible ways of pairing elements from two
lists can be defined using the do notation as follows:
~~~~~{.haskell}
pairs :: [a] -> [b] -> [(a,b)]
pairs xs ys = do x <- xs
y <- ys
return (x, y)
~~~~~
That is, consider each possible value `x` from the list `xs`, and
each value `y` from the list `ys`, and return the pair `(x,y)`. It
is interesting to note the similarity to how this function
would be defined using the list comprehension notation:
~~~~~{.haskell}
pairs xs ys = [(x, y) | x <- xs, y <- ys]
~~~~~
or in Python syntax:
~~~~~{.haskell}
def pairs(xs, ys): return [(x,y) for x in xs for y in ys]
~~~~~
In fact, there is a formal connection between the `do` notation
and the comprehension notation. Both are simply different
shorthands for repeated use of the `>>=` operator for lists.
Indeed, the language *Gofer* that was one of the precursors
to Haskell permitted the comprehension notation to be used
with any monad. For simplicity however, Haskell only allows
the comprehension notation to be used with lists.
**List Monad Example**
~~~~~{.haskell}
-- (>>=) :: [a] -> (a -> [b]) -> [b]
[] >>= _ = []
(x:xs) >>= f = f x ++ (xs >>= f)
[x1] >>= f = f x1
[x1,x2] >>= f = f x1 ++ f x2
[x1,x2,x3] >>= f = f x1 ++ f x2 ++ f x3
~~~~~
Lets define a function:
~~~~~{.haskell}
foo :: [Int] -> [Char]
foo xs = do x <- xs
show (x+1)
~~~~~
What happens when we run:
~~~~~{.haskell}
foo [11, 22, 33, 44]
= do x <- [11, 22, 33, 44]
show (x+1)
= [11,22,33,44] >>= (\x -> show (x+1))
= (\x -> show (x+1)) 11
++ (\x -> show (x+1)) 22
++ (\x -> show (x+1)) 33
++ (\x -> show (x+1)) 44
= (show (11+1))
++ (show (22+1))
++ (show (33+1))
++ (show (44+1))
= (show 12)
++ (show 23)
++ (show 34)
++ (show 45)
= "12233445"
~~~~~
Imperative Functional Programming
=================================
Consider the following problem. I have a (finite) list of values, e.g.
\begin{code}
vals0 :: [Char]
vals0 = ['d', 'b', 'd', 'd', 'a']
\end{code}
that I want to *canonize* into a list of integers, where each *distinct*
value gets the next highest number. So I want to see something like
~~~~~{.haskell}
ghci> canonize vals0
[0, 1, 0, 0, 2]
~~~~~
similarly, I want:
~~~~~{.haskell}
ghci> canonize ["zebra", "mouse", "zebra", "zebra", "owl"]
[0, 1, 0, 0, 2]
~~~~~
**DO IN CLASS**
How would you write `canonize` in Python?
**DO IN CLASS**
How would you write `canonize` in Haskell?
Now, lets look at another problem. Consider the following tree datatype.
~~~~~{.haskell}
data Tree a = Leaf a
| Node (Tree a) (Tree a)
deriving (Eq, Show)
~~~~~
Lets write a function
~~~~~{.haskell}
leafLabel :: Tree a -> Tree (a, Int)
~~~~~
that assigns each leaf a distinct integer value, so we get the following
behavior
~~~~~{.haskell}
ghci> leafLabel (Node (Node (Leaf 'a') (Leaf 'b')) (Leaf 'c'))
(Node (Node (Leaf ('a', 0)) (Leaf ('b', 1))) (Leaf ('c', 2)))
~~~~~
**DO IN CLASS**
How would you write `leafLabel` in Haskell?
The State Monad
===============
Now let us consider the problem of writing functions that
manipulate some kind of state, represented by a type whose
internal details are not important for the moment:
~~~~~{.haskell}
type State = ...
~~~~~
The most basic form of function on this type is a *state transformer*
(abbreviated by ST), which takes the current state as its argument,
and produces a modified state as its result, in which the modified
state reflects any side effects performed by the function:
~~~~~{.haskell}
type ST = State -> State
~~~~~
In general, however, we may wish to return a result value in
addition to updating the state. For example, a function for
incrementing a counter may wish to return the current value
of the counter. For this reason, we generalise our type of
state transformers to also return a result value, with the
type of such values being a parameter of the `ST` type:
~~~~~{.haskell}
type ST a = State -> (a, State)
instance Monad ST where
-- return :: a -> ST a
return x = \st -> (x, st)
-- >>= :: ST a -> (a -> ST b) -> ST b
ma >>= f = \st ->
let (soma, st') = (ma st)
(somb, st'') = (f soma st')
in
(somb, st'')
-- >>= :: ST a -> (a -> ST b) -> ST b
tx1 >>= f = \st -> let (v, st') = tx1 st in
tx2 = f v
in tx2 st'
~~~~~
Such functions can be depicted as follows, where `s` is the input
state, `s'` is the output state, and `v` is the result value:
<img src="../static/monad1.png" width="300"/>
The state transformer may also wish to take argument values.
However, there is no need to further generalise the `ST` type
to take account of this, because this behaviour can already
be achieved by exploiting currying. For example, a state
transformer that takes a character and returns an integer
would have type `Char -> ST Int`, which abbreviates the
curried function type
~~~~~{.haskell}
Char -> State -> (Int, State)
~~~~~
depicted by:
<img src="../static/monad2.png" width="300"/>
Returning to the subject of monads, it is now straightforward
to make `ST` into an instance of a monadic type:
~~~~~{.haskell}
instance Monad ST where
-- return :: a -> ST a
return x = \s -> (x,s)
-- (>>=) :: ST a -> (a -> ST b) -> ST b
st >>= f = \s -> let (x,s') = st s in f x s'
~~~~~
That is, `return` converts a value into a state transformer that
simply returns that value without modifying the state:
<img src="../static/monad3.png" width="300"/>
In turn, `>>=` provides a means of sequencing state transformers:
`st >>= f` applies the state transformer `st` to an initial state
`s`, then applies the function `f` to the resulting value `x` to
give a second state transformer `(f x)`, which is then applied
to the modified state `s'` to give the final result:
<img src="../static/monad4.png" width="400"/>
Note that `return` could also be defined by `return x s = (x,s)`.
However, we prefer the above definition in which the second
argument `s` is shunted to the body of the definition using a
lambda abstraction, because it makes explicit that `return` is
a function that takes a single argument and returns a state
transformer, as expressed by the type `a -> ST a`: A similar
comment applies to the above definition for `>>=`.
We conclude this section with a technical aside. In Haskell,
types defined using the `type` mechanism cannot be made into
instances of classes. Hence, in order to make ST into an
instance of the class of monadic types, in reality it needs
to be redefined using the `data` mechanism, which requires
introducing a dummy constructor (called `S` for brevity):
\begin{code}
data ST0 a = S0 (State -> (a, State))
\end{code}