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
|
<title>A Gentle Introduction to Haskell: Standard Classes</title>
<p>
<body bgcolor="#ffffff"><i>A Gentle Introduction to Haskell, Version 1.4</i><br><a href="io.html">back</a> <a href="modules.html">next</a> <a href="index.html">top</a><hr>
<p>
<a name="sect8"></a>
<h2>8<tt> </tt>Standard Haskell Classes</h2><p>
In this section we introduce the predefined standard type
classes in Haskell. We have simplified these classes somewhat by
omitting some of the less interesting methods in these classes; the
Haskell report contains a more complete description. Also, some of
the standard classes are part of the standard Haskell libraries; these
are described in the Haskell Library Report.<p>
<div align=center><img src="fig3.gif" alt="Standard Haskell Classes">
<h4>Figure 3</h4> </div>
<p>
<a name="sect8.1"></a>
<h3>8.1<tt> </tt>Equality and Ordered Classes</h3><p>
Haskell's standard classes form the somewhat imposing inclusion
structure shown in Figure 3. At the top of the
figure, we see <tt>Eq</tt> with its subclass <tt>Ord</tt> below it.
These were defined in the previous section. <a name="tut-enum-classes"></a><p>
<a name="sect8.2"></a>
<h3>8.2<tt> </tt>The Enumeration Class</h3>
<p>
Class <tt>Enum</tt> has a set of operations that underlie the syntactic sugar of
arithmetic sequences; for example, the arithmetic sequence expression
<tt>[1,3..]</tt> stands for <tt>enumFromThen 1 3</tt> (see
<a href="../report/exps.html#arithmetic-sequences">§3.10</a> for the formal translation).
We can now see that arithmetic sequence expressions can be used to
generate lists of any type that is an instance of <tt>Enum</tt>. This
includes not only most numeric types, but also <tt>Char</tt>, so that, for
instance, <tt>['a'..'z']</tt> denotes the list of lower-case letters in
alphabetical order. Furthermore, user-defined enumerated types like
<tt>Color</tt> can easily be given <tt>Enum</tt> instance declarations. If so:
<p>
<tt>[Red..Violet]</tt> => <tt>[Red, Green, Blue, Indigo, Violet]
<p>
</tt>Note that such a sequence is <I>arithmetic</I> in the sense that the
increment between values is constant, even though the values are not
numbers. Most types in <tt>Enum</tt> can be mapped onto integers; for these,
the <tt>fromEnum</tt> and <tt>toEnum</tt> convert between <tt>Int</tt> and a type in <tt>Enum</tt>.<a name="tut-text-class"></a><p>
<a name="sect8.3"></a>
<h3>8.3<tt> </tt>The Read and Show Classes</h3>
<p>
The instances of class <tt>Show</tt> are those types that can be converted
to character strings (typically for I/O). The class <tt>Read</tt>
provides operations for parsing character strings to obtain the values
they may represent. As the primitive operations in these classes are
somewhat esoteric, let's begin with one of the higher-level functions that
is defined in terms of them:
<tt><br>
<br>
show :: (Show a) => a -> String<br>
<br>
</tt>Naturally enough, <tt>show</tt> takes any value of an appropriate type and
returns its representation as a character string (list of characters),
as in <tt>show (2+2)</tt>, which results in <tt>"4"</tt>. This is fine as far as
it goes, but we typically need to produce more complex strings
that may have the representations of many values in them, as in
<tt><br>
<br>
"The sum of " ++ show x ++ " and " ++ show y ++ " is " ++ show (x+y) ++ "."<br>
<br>
</tt>and after a while, all that concatenation gets to be a bit
inefficient. Specifically, let's consider a function to represent
the binary trees of Section <a href="goodies.html#tut-recursive-types">2.2.1</a> as a string,
with suitable markings to show the nesting of subtrees and the
separation of left and right branches (provided the element type is
representable as a string):
<tt><br>
<br>
showTree :: (Show a) => Tree a -> String<br>
showTree (Leaf x) = show x<br>
showTree (Branch l r) = "<" ++ showTree l ++ "|" ++ showTree r ++ ">"<br>
<br>
</tt>Because <tt>(++)</tt> has time complexity linear in the length of its
left argument, <tt>showTree</tt> is quadratic in the size of the tree.<p>
To restore linear complexity, the function <tt>shows</tt> is provided:
<tt><br>
<br>
shows :: (Show a) => a -> String -> String<br>
<br>
shows</tt> takes a printable value and a string and returns
that string with the value's representation concatenated
at the front. The second argument serves as a sort of string
accumulator, and <tt>show</tt> can now be defined as <tt>shows</tt> with
the null accumulator:
<tt><br>
<br>
show x = shows x ""<br>
<br>
</tt>We can use <tt>shows</tt> to define a more efficient version of <tt>showTree</tt>,
which also has a string accumulator argument:
<tt><br>
<br>
showsTree :: (Show a) => Tree a -> String -> String<br>
showsTree (Leaf x) s = shows x s<br>
showsTree (Branch l r) s= '<' : showsTree l ('|' : showsTree r ('>' : s))<br>
<br>
</tt>This solves our efficiency problem (<tt>showsTree</tt> has linear complexity),
but the presentation of this function (and others like it) can be
improved. First, let's create a type synonym:
<tt><br>
<br>
type ShowS = String -> String<br>
<br>
</tt>This is the type of a function that returns a string representation of
something followed by an accumulator string.
Second, we can avoid carrying accumulators around, and also avoid
amassing parentheses at the right end of long constructions, by using
functional composition:
<tt><br>
<br>
showsTree :: (Show a) => Tree a -> ShowS<br>
showsTree (Leaf x) = shows x<br>
showsTree (Branch l r) = ('<':) . showsTree l . ('|':) . showsTree r . ('>':)<br>
<br>
</tt>Something more important than just tidying up the code has come about
by this transformation: We have raised the presentation from an
<I>object level</I> (in this case, strings) to a <I>function level.
</I>We can think of the typing as saying that <tt>showsTree</tt> maps a tree
into a <I>showing function</I>. Functions like <tt>('<' :)</tt> or
<tt>("a string" ++)</tt> are primitive showing functions, and we build up
more complex functions by function composition.<p>
Now that we can turn trees into strings, let's turn to the inverse
problem. The basic idea is a parser for a type <tt>a</tt>, which
is a function that takes a string and returns a list of <tt>(a, String)
</tt>pairs[<a href="haskell-tutorial.html#$wadler:list-of-successes">8</a>]. The Prelude provides
a type synonym for such functions:
<tt><br>
<br>
type ReadS a = String -> [(a,String)]<br>
<br>
</tt>Normally, a parser returns a singleton list, containing a value
of type <tt>a</tt> that was read from the input string and the remaining
string that follows what was parsed. If no parse was possible, however,
the result is the empty list, and if there is more than one possible
parse (an ambiguity), the resulting list contains more than one pair.
The standard function <tt>reads</tt> is a parser for any instance of <tt>Read</tt>:
<tt><br>
<br>
reads :: (Read a) => ReadS a<br>
<br>
</tt>We can use this function to define a parsing function for the string
representation of binary trees produced by <tt>showsTree</tt>. List comprehensions
give us a convenient idiom for constructing such parsers (An
even more elegant approach to parsing uses monads and parser
combinators. These are part of a standard parsing library distributed
with most Haskell systems.):
<tt><br>
<br>
readsTree :: (Read a) => ReadS (Tree a)<br>
readsTree ('<':s) = [(Branch l r, u) | (l, '|':t) <- readsTree s,<br>
(r, '>':u) <- readsTree t ]<br>
readsTree s = [(Leaf x, t) | (x,t) <- reads s]<br>
<br>
</tt>Let's take a moment to examine this function definition in detail.
There are two main cases to consider: If the first character of the
string to be parsed is <tt>'<'</tt>, we should have the representation of
a branch; otherwise, we have a leaf. In the first case, calling the
rest of the input string following the opening angle bracket <tt>s</tt>,
any possible parse must be a tree <tt>Branch l r</tt> with remaining string <tt>u</tt>,
subject to the following conditions:
<OL><LI>
The tree <tt>l</tt> can be parsed from the beginning of the string <tt>s</tt>.
<LI>
The string remaining (following the representation of <tt>l</tt>) begins
with <tt>'|'</tt>. Call the tail of this string <tt>t</tt>.
<LI>
The tree <tt>r</tt> can be parsed from the beginning of <tt>t</tt>.
<LI>
The string remaining from that parse begins with <tt>'>'</tt>, and
<tt>u</tt> is the tail.
</OL>
Notice the expressive power we get from the combination of pattern
matching with list comprehension: The form of a resulting parse is
given by the main expression of the list comprehension, the first
two conditions above are expressed by the first generator
("<tt>(l, '|':t)</tt> is drawn from the list of parses of <tt>s</tt>."), and the
remaining conditions are expressed by the second generator.<p>
The second defining equation above just says that to parse the
representation of a leaf, we parse a representation of the element
type of the tree and apply the constructor <tt>Leaf</tt> to the value thus
obtained.<p>
We'll accept on faith for the moment that there is a <tt>Read</tt> (and
<tt>Show</tt>) instance
of <tt>Int</tt> (among many other types), providing a <tt>reads</tt> that behaves
as one would expect, e.g.:
<p>
<tt>(reads "5 golden rings") :: [(Int,String)]</tt> => <tt>[(5, " golden rings")]</tt> <p>
With this understanding, the reader should verify the following evaluations:
<p>
<table >
<tr><td>
<tt>readsTree "<1|<2|3>>"</tt></td><td align=center> => </td><td>
<tt>[(Branch (Leaf 1) (Branch (Leaf 2) (Leaf 3)), "")]</tt></td></tr><tr><td><tt>readsTree "<1|2"</tt> </td><td align=center> => </td><td> <tt>[]
</tt></td></tr></table>
<p>
<p>
There are a couple of shortcomings in our definition of <tt>readsTree</tt>.
One is that the parser is quite rigid, allowing no white space before
or between the elements of the tree representation; the other is that
the way we parse our punctuation symbols is quite different from the
way we parse leaf values and subtrees, this lack of uniformity making
the function definition harder to read. We can address both of these
problems by using the lexical analyzer provided by the Prelude:
<tt><br>
<br>
lex :: ReadS String<br>
<br>
lex</tt> normally returns a singleton list containing a
pair of strings: the first lexeme in the input string and the remainder
of the input. The lexical rules are those of Haskell programs,
including comments, which <tt>lex</tt> skips, along with whitespace.
If the input string is empty or contains only whitespace and comments,
<tt>lex</tt> returns <tt>[("","")]</tt>; if the input is not empty in this sense,
but also does not begin with a valid lexeme after any leading whitespace
and comments, <tt>lex</tt> returns <tt>[]</tt>.<p>
Using the lexical analyzer, our tree parser now looks like this:
<tt><br>
<br>
readsTree :: (Read a) => ReadS (Tree a)<br>
readsTree s = [(Branch l r, x) | ("<", t) <- lex s,<br>
(l, u) <- readsTree t,<br>
("|", v) <- lex u,<br>
(r, w) <- readsTree v,<br>
(">", x) <- lex w ]<br>
++<br>
[(Leaf x, t) | (x, t) <- reads s ]<br>
<br>
<p>
</tt>We may now wish to use <tt>readsTree</tt> and <tt>showsTree</tt> to declare
<tt>(Read a) => Tree a</tt> an instance of <tt>Read</tt> and <tt>(Show a) => Tree a</tt> an
instance of <tt>Show</tt>. This would allow us to
use the generic overloaded functions from the Prelude to parse and
display trees. Moreover, we would automatically then be able to parse
and display many other types containing trees as components, for
example, <tt>[Tree Int]</tt>. As it turns out, <tt>readsTree</tt> and <tt>showsTree
</tt>are of almost the right types to be <tt>Show</tt> and <tt>Read</tt> methods, needing
only the addition of an extra parameter each that has do do with
parenthesization of forms with infix constructors. We refer the
interested reader to <a href="../report/derived.html#derived-appendix">§D</a> for details.<p>
We can test the <tt>Read</tt> and <tt>Show</tt> instances by applying <tt>(read . show)
</tt>(which should be the identity) to some trees, where <tt>read</tt> is a
specialization of <tt>reads</tt>:
<tt><br>
<br>
read :: (Read a) => String -> a<br>
<br>
</tt>This function fails if there is not a unique parse or if the input
contains anything more than a representation of one value of type <tt>a
</tt>(and possibly, comments and whitespace).<a name="tut-derived-instances"></a><p>
<a name="sect8.4"></a>
<h3>8.4<tt> </tt>Derived Instances</h3>
<p>
Recall the <tt>Eq</tt> instance for trees we presented in Section
<a href="classes.html#tut-type-classes">5</a>; such a declaration is
simple---and boring---to produce: We require that the
element type in the leaves be an equality type; then, two leaves are
equal iff they contain equal elements, and two branches are equal iff
their left and right subtrees are equal, respectively. Any other two
trees are unequal:
<tt><br>
<br>
instance (Eq a) => Eq (Tree a) where<br>
(Leaf x) == (Leaf y) = x == y<br>
(Branch l r) == (Branch l' r') = l == l' && r == r'<br>
_ == _ = False<br>
<br>
<p>
</tt>Fortunately, we don't need to go through this tedium every time we
need equality operators for a new type; the <tt>Eq</tt> instance can be
<I>derived automatically</I> from the <tt>data</tt> declaration if we so specify:
<tt><br>
<br>
data Tree a = Leaf a | Branch (Tree a) (Tree a) deriving Eq<br>
<br>
</tt>The <tt>deriving</tt> clause implicitly produces an <tt>Eq</tt> instance declaration
just like the one in Section <a href="classes.html#tut-type-classes">5</a>. Instances of <tt>Ord</tt>,
<tt>Enum</tt>, <tt>Ix</tt>, <tt>Read</tt>, and <tt>Show</tt> can also be generated by the
<tt>deriving</tt> clause.
[More than one class name can be specified, in which case the list
of names must be parenthesized and the names separated by commas.]<p>
The derived <tt>Ord</tt> instance for <tt>Tree</tt> is slightly more complicated than
the <tt>Eq</tt> instance:
<tt><br>
<br>
instance (Ord a) => Ord (Tree a) where<br>
(Leaf _) <= (Branch _) = True<br>
(Leaf x) <= (Leaf y) = x <= y<br>
(Branch _) <= (Leaf _) = False<br>
(Branch l r) <= (Branch l' r') = l == l' && r <= r' || l <= l'<br>
<br>
</tt>This specifies a <I>lexicographic</I> order: Constructors are ordered
by the order of their appearance in the <tt>data</tt> declaration, and the
arguments of a constructor are compared from left to right. Recall
that the built-in list type is semantically equivalent to an ordinary
two-constructor type. In fact, this is the full declaration:
<tt><br>
<br>
data [a] = [] | a : [a] deriving (Eq, Ord) -- pseudo-code<br>
<br>
</tt>(Lists also have a <tt>Text</tt> instance, which is not derived.)
The derived <tt>Eq</tt> and <tt>Ord</tt> instances for lists are the usual ones; in
particular, character strings, as lists of characters, are ordered as
determined by the underlying <tt>Char</tt> type, with an initial substring
comparing less than a longer string; for example, <tt>"cat" < "catalog"</tt>.<p>
In practice, <tt>Eq</tt> and <tt>Ord</tt> instances are almost always derived,
rather than user-defined. In fact, we should provide our own
definitions of equality and ordering predicates only with some
trepidation, being careful to maintain the expected algebraic
properties of equivalence relations and total orders.
An intransitive <tt>(==)</tt> predicate, for example, could be disastrous,
confusing readers of the program and confounding manual or
automatic program transformations that rely on the <tt>(==)</tt> predicate's
being an approximation to definitional equality. Nevertheless,
it is sometimes necessary to provide <tt>Eq</tt> or <tt>Ord</tt> instances
different from those that would be derived; probably the most
important example is that of an abstract data type in which different
concrete values may represent the same abstract value.<p>
An enumerated type can have a derived <tt>Enum</tt> instance, and here again,
the ordering is that of the constructors in the <tt>data</tt> declaration.
For example:
<tt><br>
<br>
data Day = Sunday | Monday | Tuesday | Wednesday<br>
| Thursday | Friday | Saturday deriving (Enum)<br>
<br>
</tt>Here are some simple examples using the derived instances for this type:
<p>
<table >
<tr><td>
<tt>[Wednesday..Friday]</tt> </td><td align=center>=></td><td> <tt>[Wednesday, Thursday, Friday]</tt></td></tr><tr><td><tt>[Monday, Wednesday ..]</tt> </td><td align=center>=></td><td> <tt>[Monday, Wednesday, Friday]
</tt></td></tr></table>
<p>
<p>
Derived <tt>Read</tt> (<tt>Show</tt>) instances are possible for all types
whose component types also have <tt>Read</tt> (<tt>Show</tt>) instances.
(<tt>Read</tt> and <tt>Show</tt> instances for most of the standard types
are provided by the Prelude. Some types, such as the function type <tt>(->)</tt>,
have a <tt>Show</tt> instance but not a corresponding <tt>Read</tt>.) The textual
representation
defined by a derived <tt>Show</tt> instance is consistent with the
appearance of constant Haskell expressions of the type in question.
For example, if we add <tt>Show</tt> and <tt>Read</tt> to the <tt>deriving</tt> clause for type
<tt>Day</tt>, above, we obtain
<p>
<tt>show [Monday..Wednesday]</tt> =>
<tt>"[Monday,Tuesday,Wednesday]"
<p>
<a name="tut-monadic-classes"></a><p>
</tt><a name="sect8.5"></a>
<h3>8.5<tt> </tt>Monadic Classes</h3>
The Prelude contains a number of classes which are related to the
mathematical notion of a "monad." While the terminology used is
derived from category theory, it is not necessary to delve into
abstract mathematics to get an intuitive understanding of what these
classes do. Indeed, although the names of the classes and methods may
seem unusual, these monadic operations are very useful for general
programming.<p>
Monads are built on polymorphic types such as lists. The
monad is defined by a set of instances in the monadic classes for this
underlying polymorphic type.<p>
Mathematically, monads are defined by set of laws which govern the monadic
operations. Haskell includes other overloaded operations that are
governed by laws, at least
informally. For example, <tt>x /= y</tt> and <tt>not (x == y)</tt> ought to be the
same. However, since both <tt>==</tt> and <tt>/=</tt> are
class methods in the <tt>Eq</tt> class, there is no way to assure that <tt>==</tt> and
<tt>=/</tt> are related in this manner for arbitrary instances of <tt>Eq</tt>.
In the same sense, the monadic laws presented here are not enforced by
Haskell, but should be obeyed by all instances of a monadic class.<p>
There are four classes associated with monads: <tt>Functor</tt>, <tt>Monad</tt>,
<tt>MonadZero</tt>, and <tt>MonadPlus</tt>; none of them are derivable. In addition
to <tt>IO</tt>, two other types in the Prelude are members of the monadic
classes: lists (<tt>[]</tt>) and exceptions (<tt>Maybe</tt>). We will discuss only
the instances for
lists. The <tt>Maybe</tt> type behaves as a truncated list in monadic
operations: <tt>Nothing</tt> is the same as <tt>[]</tt> and <tt>Just x</tt> is the same as
<tt>[x]</tt>.<p>
The <tt>Functor</tt> class, already discussed in section
<a href="classes.html#tut-type-classes">5</a>, defines a
single operation: <tt>map</tt>. The map function applies an operation to the
objects inside a container (polymorphic types can be thought of as
containers for values of another type), returning a container of the
same shape.
These laws apply to <tt>map</tt> in the class <tt>Functor</tt>:
<p>
<table >
<tr><td>
<tt>map id</tt></td><td align=center>=</td><td><tt>id</tt></td></tr><tr><td><tt>map (f . g)</tt></td><td align=center>=</td><td><tt>map f . map g</tt></td></tr></table>
<p>
These laws ensure that the container shape is unchanged by
<tt>map</tt> and that the contents of the container are not re-arranged by
the mapping operation. <p>
The <tt>Monad</tt> class defines two basic operators: <tt>>>=</tt> (bind) and <tt>return</tt>.
<tt><br>
<br>
class Monad m where<br>
(>>=) :: m a -> (a -> m b) -> m b<br>
(>>) :: m a -> m b -> m b<br>
return :: a -> m a<br>
<br>
m >> k = m >>= \_ -> k<br>
<br>
</tt>The bind operations, <tt>>></tt> and <tt>>>=</tt>, combine two monadic values while
the <tt>return</tt> operation injects a value into the monad (container).
The signature of <tt>>>=</tt>, <tt>Monad m => m a -> (a -> m b) -> m b</tt>, helps
us to understand this operation: <tt>ma >>= \v -> mb</tt>
combines a monadic value <tt>ma</tt> containing values
of type <tt>a</tt> and a function which operates
on a value <tt>v</tt> of type <tt>a</tt> returns the monadic value <tt>mb</tt>. The
result is to combine <tt>ma</tt> and <tt>mb</tt> into a
monadic value containing <tt>b</tt>. The <tt>>></tt>
function is used when the function does not need the value produced by
the first monadic operator. The exact
meaning of binding depends of the particular monad being used. For
example, in the IO monad, <tt>x >>= y</tt> performs two actions sequentially,
passing the result of the first into the second. For lists, you can
think of the monadic functions
as dealing with multiple values. Monadic binding takes
a set (list) of values and applies a function to each of them,
collecting all generated values together. The <tt>return</tt> function
creates a singleton list. <p>
Monadic list operations should already be familiar: list
comprehensions (as well as <tt>do</tt> expressions) are actually syntactic
sugar for monadic operators. In fact, in spite of their name, list
comprehensions can be used with arbitrary monads.
These following three expressions are all different syntax for the
same thing:
<tt><br>
<br>
[(x,y) | x <- [1,2,3] , y <- [4,5,6]]<br>
<br>
do x <- [1,2,3]<br>
y <- [4,5,6]<br>
return (x,y)<br>
<br>
[1,2,3] >>= (\ x -> [4,5,6] >>= (\y -> return (x,y)))<br>
<br>
<p>
</tt>The laws which govern <tt>>>=</tt> and <tt>return</tt> are:
<p>
<table >
<tr><td>
<tt>return a >>= k</tt></td><td align=center>=</td><td><tt>k a</tt> </td></tr><tr><td><tt>m >>= return</tt></td><td align=center>=</td><td><tt>m</tt> </td></tr><tr><td><tt>map f xs</tt></td><td align=center>=</td><td><tt>xs >>= return . f</tt></td></tr><tr><td><tt>m >>= (\x -> k x >>= h))</tt></td><td align=center>=</td><td><tt>(m >>= k) >>= h</tt></td></tr></table>
<p>
<p>
The class <tt>MonadZero</tt> is used for monads that have a <I>zero</I> element:
<tt><br>
<br>
class (Monad m) => MonadZero m where<br>
zero :: m a<br>
<br>
</tt>The zero element obeys the following laws:
<p>
<table >
<tr><td>
<tt>m >>= \x -> zero</tt></td><td align=center>=</td><td><tt>zero</tt></td></tr><tr><td><tt>zero >>= m</tt></td><td align=center>=</td><td><tt>zero</tt></td></tr></table>
<p>
For lists, the zero value is <tt>[]</tt>, the empty list. The I/O monad has
no zero element and is not a member of this class.<p>
The class <tt>MonadPlus</tt> contains monads which have a plus
operation which combines the contents of two containers:
<tt><br>
<br>
class (MonadZero m) => MonadPlus m where<br>
(++) :: m a -> m a -> m a<br>
<br>
</tt>Instances of <tt>MonadPlus</tt> should obey the following laws:
<p>
<table >
<tr><td>
<tt>m ++ zero</tt></td><td align=center>=</td><td><tt>m</tt></td></tr><tr><td><tt>zero ++ m</tt></td><td align=center>=</td><td><tt>m</tt></td></tr></table>
<p>
The <tt>++</tt> operator is ordinary list concatenation in the list monad.<p>
<hr><body bgcolor="#ffffff"><i>A Gentle Introduction to Haskell, Version 1.4</i><br><a href="io.html">back</a> <a href="modules.html">next</a> <a href="index.html">top</a>
<p>
|