summaryrefslogtreecommitdiff
path: root/Haskell-book/18/Instance/src/Sum.hs
blob: d51b211b2a50cd2b7971058d199fa2734326264b (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
28
29
30
31
module Sum where

import Test.QuickCheck
import Test.QuickCheck.Checkers

data Sum a b =
    First a
  | Second b
  deriving (Eq, Show)

instance Functor (Sum a) where
    fmap f (First x) = First x
    fmap f (Second x) = Second $ f x

instance Applicative (Sum a) where
    pure x = Second x
    First f <*> _ = First f
    Second f <*> x = fmap f x

instance Monad (Sum a) where
    return = pure
    (First x) >>= f = First x
    (Second x) >>= f = f x

instance (Arbitrary a, Arbitrary b) => Arbitrary (Sum a b) where
    arbitrary = frequency [ (1, fmap First arbitrary)
                          , (1, fmap Second arbitrary)
                          ]

instance (Eq a, Eq b) => EqProp (Sum a b) where
    (=-=) = eq