-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmonoids.hs
More file actions
55 lines (36 loc) · 774 Bytes
/
Copy pathmonoids.hs
File metadata and controls
55 lines (36 loc) · 774 Bytes
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
GHCi> (5 + 6) + 10
21
GHCi> 5 + (6 + 10)
21
(5 + 6) + 10
5 + (6 + 10)
(5 - 6) - 10
5 - (6 - 10)
:{
class Monoid a where
mempty :: a
mappend :: a -> a -> a
mconcat :: [a] -> a
mconcat = foldr mappend mempty
:}
:{
instance Monoid [a] where
mempty = []
mappend = (++)
:}
mconcat :: [a] -> a
mconcat = foldr mappend mempty
-- | Monoid under addition.
newtype Sum a = Sum { getSum :: a }
-- | Monoid under multiplication.
newtype Product a = Product { getProduct :: a }
:{
instance Num a => Monoid (Sum a) where
mempty = Sum 0
Sum x `mappend` Sum y = Sum (x + y)
:}
(<>) Sum 5 Sum 6
Sum 5 <> Sum 6 <> Sum 10
instance Num a => Monoid (Product a) where
mempty = Product 1
Product x `mappend` Product y = Product (x * y)