-
-
Save mauriciofierrom/bdb7a5d0ff06c4a23b51ef7bfa7d81d9 to your computer and use it in GitHub Desktop.
Validation re-write
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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