Skip to content

Commit 69959e0

Browse files
Show Either's "do notation" similarity to nested if-then-else statement (#52)
* Show Either's "do notation" similarity to nested if-then-else statement * Move `Either` "do notation" explanation from Monad to Bind instance This move also uses PureScript to show the code that this notation ultimately produces
1 parent 9090158 commit 69959e0

File tree

1 file changed

+29
-7
lines changed

1 file changed

+29
-7
lines changed

src/Data/Either.purs

Lines changed: 29 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -125,24 +125,46 @@ instance altEither :: Alt (Either e) where
125125
-- | Left x >>= f = Left x
126126
-- | Right x >>= f = f x
127127
-- | ```
128-
instance bindEither :: Bind (Either e) where
129-
bind = either (\e _ -> Left e) (\a f -> f a)
130-
131-
-- | The `Monad` instance guarantees that there are both `Applicative` and
132-
-- | `Bind` instances for `Either`. This also enables the `do` syntactic sugar:
133128
-- |
129+
-- | `Either`'s "do notation" can be understood to work like this:
134130
-- | ``` purescript
135-
-- | do
131+
-- | x :: forall e a. Either e a
132+
-- | x = --
133+
-- |
134+
-- | y :: forall e b. Either e b
135+
-- | y = --
136+
-- |
137+
-- | foo :: forall e a. (a -> b -> c) -> Either e c
138+
-- | foo f = do
136139
-- | x' <- x
137140
-- | y' <- y
138141
-- | pure (f x' y')
139142
-- | ```
140143
-- |
141-
-- | Which is equivalent to:
144+
-- | ...which is equivalent to...
142145
-- |
143146
-- | ``` purescript
144147
-- | x >>= (\x' -> y >>= (\y' -> pure (f x' y')))
145148
-- | ```
149+
-- |
150+
-- | ...and is the same as writing...
151+
-- |
152+
-- | ```
153+
-- | foo :: forall e a. (a -> b -> c) -> Either e c
154+
-- | foo f = case x of
155+
-- | Left e ->
156+
-- | Left e
157+
-- | Right x -> case y of
158+
-- | Left e ->
159+
-- | Left e
160+
-- | Right y ->
161+
-- | Right (f x y)
162+
-- | ```
163+
instance bindEither :: Bind (Either e) where
164+
bind = either (\e _ -> Left e) (\a f -> f a)
165+
166+
-- | The `Monad` instance guarantees that there are both `Applicative` and
167+
-- | `Bind` instances for `Either`.
146168
instance monadEither :: Monad (Either e)
147169

148170
-- | The `Extend` instance allows sequencing of `Either` values and functions

0 commit comments

Comments
 (0)