. >>=
, a -> m b
m
.
:
-, ( >>=
), - IO
.
( , IO
) . , Maybe a
, .
Maybe a
"". ( Just x
) " " ( Nothing
).
>>=
f :: a -> Maybe b
. , f
, . / . , >>=
, , .
, : . (++ " hello")
, ( :().
, , . return
( , ). :
getContents >>= return . (++ " hello") >>= putStrLn
, "", "" () . , putStrLn
String -> IO ()
. , putStrLn
- , , ()
( , , ()
: ()
).
, , :
getContents >>= putStrLn . (++ " hello")
, , :
a >>= b >>= c >>= d >>= e
, a
. bind b
. b
( / c
). bind c
..
I/O
/ . " -", , . bind "IO" ( >>=
, , -) . , , , .
Maybe
revisited
I/O - - , . Maybe
. , Maybe
:
data Maybe a = Nothing | Just a
Nothing
:
+
/ /|
+
| |/
+
Just x
:
+
/ /|
+
| x |/
+
. , , , , , Just x
x
. , . Maybe
>>=
.
:
instance Monad Maybe where
return x = Just x
(>>=) Nothing _ = Nothing
(>>=) (Just x) f = f x
return
, Maybe
", return
" ".
bind . , , Nothing
.
, x
, f
, , f
. >>=
. / " ".
, somthing like:
Just 2 >>= Just . (+5) >>= Just . (*6)
Just 42
. ? , a 2
. >>=
Just . (+2)
, (Just . (+2)) 2
. , Just
of Just 2
. , , Just 7
.
This package opens again and guesses what it contains 7
, is now 7
processed by the last function Just . (*6)
, so the last function will multiply it by 6
and wrap it in the field again.
If you, however, write:
Just 2 >>= (+5) >>= Just . (*6)
it will fail. What for? Because, apparently, the second function is not in a good mood and forgot to wrap your gift in a box.