Skip to content

Functor/Foldable/TraversableWithIndex #42

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 1 commit into from
Oct 28, 2018
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
18 changes: 18 additions & 0 deletions src/Data/Either.purs
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,13 @@ import Data.Bifunctor (class Bifunctor)
import Data.Bitraversable (class Bitraversable)
import Data.Eq (class Eq1)
import Data.Foldable (class Foldable)
import Data.FoldableWithIndex (class FoldableWithIndex)
import Data.Functor.Invariant (class Invariant, imapF)
import Data.FunctorWithIndex (class FunctorWithIndex)
import Data.Maybe (Maybe(..), maybe, maybe')
import Data.Ord (class Ord1)
import Data.Traversable (class Traversable)
import Data.TraversableWithIndex (class TraversableWithIndex)

-- | The `Either` type is used to represent a choice between two types of value.
-- |
Expand All @@ -34,6 +37,9 @@ data Either a b = Left a | Right b
-- | ```
derive instance functorEither :: Functor (Either a)

instance functorWithIndexEither :: FunctorWithIndex Unit (Either a) where
mapWithIndex f = map $ f unit

instance invariantEither :: Invariant (Either a) where
imap = imapF

Expand Down Expand Up @@ -186,6 +192,14 @@ instance foldableEither :: Foldable (Either a) where
foldMap f (Left _) = mempty
foldMap f (Right x) = f x

instance foldableWithIndexEither :: FoldableWithIndex Unit (Either a) where
foldrWithIndex _ z (Left _) = z
foldrWithIndex f z (Right x) = f unit x z
foldlWithIndex _ z (Left _) = z
foldlWithIndex f z (Right x) = f unit z x
foldMapWithIndex f (Left _) = mempty
foldMapWithIndex f (Right x) = f unit x

instance bifoldableEither :: Bifoldable Either where
bifoldr f _ z (Left a) = f a z
bifoldr _ g z (Right b) = g b z
Expand All @@ -200,6 +214,10 @@ instance traversableEither :: Traversable (Either a) where
sequence (Left x) = pure (Left x)
sequence (Right x) = Right <$> x

instance traversableWithIndexEither :: TraversableWithIndex Unit (Either a) where
traverseWithIndex _ (Left x) = pure (Left x)
traverseWithIndex f (Right x) = Right <$> f unit x

instance bitraversableEither :: Bitraversable Either where
bitraverse f _ (Left a) = Left <$> f a
bitraverse _ g (Right b) = Right <$> g b
Expand Down