epogrebnyak / haskell-intro

Seven classes on Haskell and a follow-up reading list
http://tinyurl.com/haskell-intro
53 stars 6 forks source link

stupid monoid example #12

Closed epogrebnyak closed 4 years ago

epogrebnyak commented 4 years ago
data Pipe a = On a | Off | Pass deriving Show
instance (Ord a) => Semigroup (Pipe a) where
  _ <> Off = Off
  Off <> _ = Off
  Pass <> x = x
  x <> Pass = x
  (On x) <> (On y) = On (min x y) -- possibly an error   

instance (Ord a) => Monoid (Pipe a) where
  mempty = Pass
  mappend (On x) (On y) = On (min x y)
  mappend Pass x = x
  mappend x Pass = x   
  mappend _ _    = Off

k = mconcat [On 2, On 3, Pass]
epogrebnyak commented 4 years ago

See Writer and State in http://fprog.ru/2009/issue1/dan-piponi-haskell-monoids-and-their-uses/