Skip to content

Instantly share code, notes, and snippets.

@dewey92
Last active April 6, 2019 09:41
Show Gist options
  • Select an option

  • Save dewey92/52193495b9ada64b3fbd090ce2fda64f to your computer and use it in GitHub Desktop.

Select an option

Save dewey92/52193495b9ada64b3fbd090ce2fda64f to your computer and use it in GitHub Desktop.
Haskell Monoid
-- | Instance Array
-- | String is in fact an Array of Char
instance Semigroup [a] where
(<>) = (++)
instance Monoid [a] where
mempty = []
-- | Instance Num under addition
newtype Sum n = Sum n
instance Num n => Semigroup (Sum n) where
(<>) = (+)
instance Monoid (Sum n) where
mempty = 0
-- | Instance Num under multiplication
newtype Prod n = Prod n
instance Num n => Semigroup (Prod n) where
(<>) = (*)
instance Monoid (Prod n) where
mempty = 1
-- | Instance CSS Color
newtype Color = Color String
instance Semigroup Color where
a <> (Color "transparent") = a
(Color "transparent") <> b = b
a <> b = ... -- implementation
instance Monoid Color where
mempty = "transparent"
-- | Instance Function
instance Semigroup b => Semigroup (a -> b) where
f <> g = \x -> f x <> g x
instance Monoid b => Monoid (a -> b) where
mempty _ = mempty
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment