Skip to content

Instantly share code, notes, and snippets.

@el-hult
Created August 25, 2021 12:08
Show Gist options
  • Save el-hult/c5d22ad98f03a2fd78ba6a67fddc6047 to your computer and use it in GitHub Desktop.
Save el-hult/c5d22ad98f03a2fd78ba6a67fddc6047 to your computer and use it in GitHub Desktop.
A Float wrapper that implements Monoid, but not the monoid laws
-- first monoid over Floats
data MaxNum = MaxNum Float deriving (Show)
instance Semigroup MaxNum where
(MaxNum a) <> (MaxNum b) = MaxNum $ max a b
instance Monoid MaxNum where
mempty = MaxNum 0 -- N.B. this does not fulfil the monoid laws fully. consider negative values!
aOne = MaxNum 4
aTwo = MaxNum 1
aThree = aOne <> aTwo
doMaxNum = print aThree -- MaxNum 4.0
-- main :: IO ()
main = do
doMaxNum
@Icelandjack
Copy link

Icelandjack commented Sep 13, 2021

You can derive newtype MaxNum = MaxNum Float deriving Semigroup via Max Float but as you already noted the Monoid instance is invalid and you are prevented from deriving a Monoid

@el-hult
Copy link
Author

el-hult commented Sep 14, 2021

Nice! Did not know about deriving via before. :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment