In an attempt to find a quick and easy way to add different time periods, it occurred to me that I could declare them instances of Semigroup and Monoid. Are the following instantiations valid?
data TimeDuration = S Int | M Int | H Int deriving (Show, Eq)
instance Semigroup TimeDuration where
S n1 <> S n2 = S (n1 + n2)
M n1 <> M n2 = S (60 * (n1 + n2))
H n1 <> H n2 = S (3600 * (n1 + n2))
S n1 <> M n2 = S (n1 + 60 * n2)
S n1 <> H n2 = S (n1 + 3600 * n2)
M n1 <> S n2 = S (60 * n1 + n2)
M n1 <> H n2 = S (60 * n1 + 3600 * n2)
H n1 <> S n2 = S (3600 * n1 + n2)
H n1 <> M n2 = S (3600 * n1 + 60 * n2)
instance Monoid TimeDuration where
mempty = S 0
Example: mconcat [S 1, M 2, M 3, S 2, H 1] == S 3903
User leftaroundabout ask me to produce more significative example. So this is a new implementation and some examples that I hope will show better the possible variety of the results of the operation (<>)
instance Semigroup TimeDuration where
S n1 <> S n2 = S (n1 + n2)
M n1 <> M n2 = M (n1 + n2)
H n1 <> H n2 = H (n1 + n2)
S n1 <> M n2 = S (n1 + 60 * n2)
M n1 <> S n2 = S n2 <> M n1
S n1 <> H n2 = S (n1 + 3600 * n2)
H n1 <> S n2 = S n2 <> H n1
M n1 <> H n2 = M (n1 + 60 * n2)
H n1 <> M n2 = M n1 <> H n1
instance Monoid TimeDuration where
mempty = S 0
mconcat [] = S 0
mconcat xs = foldr1 (\y acc -> y <> acc) xs
-- ex. mconcat [M 2, M 3] == M 5
-- ex. mconcat [H 2, H 3] == H 5
-- ex. mconcat [M 2, M 3, S 1] == S 301
-- ex. mconcat [H 2, H 3, M 1] == M 301
-- ex. mconcat [H 2, H 3, S 1] == S 18001