Skip to content

Show Either's "do notation" similarity to nested if-then-else statement #52

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Oct 15, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 29 additions & 7 deletions src/Data/Either.purs
Original file line number Diff line number Diff line change
Expand Up @@ -125,24 +125,46 @@ instance altEither :: Alt (Either e) where
-- | Left x >>= f = Left x
-- | Right x >>= f = f x
-- | ```
instance bindEither :: Bind (Either e) where
bind = either (\e _ -> Left e) (\a f -> f a)

-- | The `Monad` instance guarantees that there are both `Applicative` and
-- | `Bind` instances for `Either`. This also enables the `do` syntactic sugar:
-- |
-- | `Either`'s "do notation" can be understood to work like this:
-- | ``` purescript
-- | do
-- | x :: forall e a. Either e a
-- | x = --
-- |
-- | y :: forall e b. Either e b
-- | y = --
-- |
-- | foo :: forall e a. (a -> b -> c) -> Either e c
-- | foo f = do
-- | x' <- x
-- | y' <- y
-- | pure (f x' y')
-- | ```
-- |
-- | Which is equivalent to:
-- | ...which is equivalent to...
-- |
-- | ``` purescript
-- | x >>= (\x' -> y >>= (\y' -> pure (f x' y')))
-- | ```
-- |
-- | ...and is the same as writing...
-- |
-- | ```
-- | foo :: forall e a. (a -> b -> c) -> Either e c
-- | foo f = case x of
-- | Left e ->
-- | Left e
-- | Right x -> case y of
-- | Left e ->
-- | Left e
-- | Right y ->
-- | Right (f x y)
-- | ```
instance bindEither :: Bind (Either e) where
bind = either (\e _ -> Left e) (\a f -> f a)

-- | The `Monad` instance guarantees that there are both `Applicative` and
-- | `Bind` instances for `Either`.
instance monadEither :: Monad (Either e)

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