Skip to content

Instantly share code, notes, and snippets.

@mauriciofierrom
Created October 12, 2018 06:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mauriciofierrom/bdb7a5d0ff06c4a23b51ef7bfa7d81d9 to your computer and use it in GitHub Desktop.
Save mauriciofierrom/bdb7a5d0ff06c4a23b51ef7bfa7d81d9 to your computer and use it in GitHub Desktop.
Validation re-write
data Validation e a
= Failure e
| Success a
deriving (Eq, Ord, Show)
instance Functor (Validation e) where
fmap _ (Failure e) = Failure e
fmap f (Success a) = Success (f a)
instance Semigroup e => Applicative (Validation e) where
pure = Success
Failure e <*> b = Failure $ case b of
Failure e' -> e <> e'
Success _ -> e
Success _ <*> Failure e = Failure e
Success f <*> Success a = Success (f a)
instance (Semigroup e, Monoid e) => Alternative (Validation e) where
empty = Failure mempty
s@Success{} <|> _ = s
_ <|> s@Success{} = s
Failure e <|> Failure e' = Failure (e <> e')
instance Foldable (Validation e) where
foldr f x (Success a) = f a x
foldr _ x (Failure _) = x
instance Traversable (Validation e) where
traverse f (Success a) = Success <$> f a
traverse _ (Failure e) = pure (Failure e)
instance Bifunctor Validation where
bimap f _ (Failure e) = Failure (f e)
bimap _ g (Success a)_ = Success (g a)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment