summaryrefslogtreecommitdiff
path: root/lec07/Sized.hs
blob: 762d8fb872e870cc7f78f70e85f55056b909e873 (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
32
33
34
35
36
37
38
39
40
41
{-# LANGUAGE GeneralizedNewtypeDeriving, FlexibleInstances #-}
module Sized where

import Data.Monoid

newtype Size = Size Int
  deriving (Eq, Ord, Show, Num)

getSize :: Size -> Int
getSize (Size i) = i

class Sized a where
  size :: a -> Size

instance Sized Size where
  size = id

-- This instance means that things like
--   (Foo, Size)
--   (Foo, (Bar, Size))
--   ...
-- are all instances of Sized.
instance Sized b => Sized (a,b) where
  size = size . snd

-- Since (<>) has been moved from Monoid to Semigroup, this little change is required

-- Old version
{-
instance Monoid Size where
  mempty  = Size 0
  mappend = (+)
-}

-- New version
instance Monoid Size where
  mempty = Size 0

instance Semigroup Size where
  (<>) = (+)