Skip to content

Commit 874ad5b

Browse files
committed
chapter 15: added semigroup exercise for AccumulateBoth type which implements another Semigroup instance for Validtion type
1 parent 6d28643 commit 874ad5b

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import Test.QuickCheck (arbitrary, Arbitrary, quickCheck, oneof)
2+
import Data.Semigroup (Semigroup, (<>))
3+
import SemigroupLaws
4+
5+
data Validation a b =
6+
Failure a | Success b
7+
deriving (Eq, Show)
8+
9+
newtype AccumulateBoth a b =
10+
AccumulateBoth (Validation a b)
11+
deriving (Eq, Show)
12+
13+
instance (Semigroup a, Semigroup b) =>
14+
Semigroup (AccumulateBoth a b) where
15+
(AccumulateBoth (Success a)) <> (AccumulateBoth (Success b)) = AccumulateBoth (Success (a <> b))
16+
(AccumulateBoth (Failure a)) <> (AccumulateBoth (Failure b)) = AccumulateBoth (Failure (a <> b))
17+
(AccumulateBoth (Failure a)) <> (AccumulateBoth (Success _)) = AccumulateBoth (Failure a)
18+
(AccumulateBoth (Success _)) <> (AccumulateBoth (Failure b)) = AccumulateBoth (Failure b)
19+
20+
instance (Arbitrary a, Arbitrary b) => Arbitrary (AccumulateBoth a b) where
21+
arbitrary = do
22+
x <- arbitrary
23+
y <- arbitrary
24+
oneof [return (AccumulateBoth (Success x)), return (AccumulateBoth (Failure y))]
25+
26+
type ValidationAssoc = AccumulateBoth String String -> AccumulateBoth String String -> AccumulateBoth String String -> Bool
27+
28+
main = quickCheck (assocLaw :: ValidationAssoc)

0 commit comments

Comments
 (0)