summaryrefslogtreecommitdiff
path: root/Haskell-book/17/ListApplicative/src/Validation.hs
blob: 5ee3e9bfaa3e42892ff8c246bbeb7793bfe05415 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
module Validation where

import Test.QuickCheck (Arbitrary(..), frequency)
import Test.QuickCheck.Checkers

data Validation e a =
    Failure e
  | Success a
  deriving (Eq, Show)

instance Functor (Validation e) where
    fmap f (Success x) = Success $ f x
    fmap f (Failure x) = Failure x

instance Monoid e => Applicative (Validation e) where
    pure = Success
    (Failure x) <*> (Success _) = Failure x
    (Success _) <*> (Failure x) = Failure x
    (Failure f) <*> (Failure y) = Failure $ mappend f y
    (Success f) <*> (Success y) = Success $ f y

instance (Arbitrary a, Arbitrary e) => Arbitrary (Validation e a) where
    arbitrary = frequency [(1, Failure <$> arbitrary),
                           (5, Success <$> arbitrary)]

instance (Eq a, Eq e) => EqProp (Validation e a) where
    (=-=) = eq