Last active
August 29, 2015 14:12
-
-
Save chrisnc/803a4577f00f33d1ff67 to your computer and use it in GitHub Desktop.
Troll Monoid
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# LANGUAGE GeneralizedNewtypeDeriving #-} | |
import Test.QuickCheck | |
import Data.Monoid | |
import Data.Word | |
newtype Troll = Troll Word64 | |
deriving (Eq, Num, Show, Arbitrary) | |
t :: Troll | |
t = 10 -- set this to anything, and it represents a new Monoid | |
instance Monoid Troll where | |
mempty = 0 | |
mappend 0 x = x -- obey the identity law by definition | |
mappend x 0 = x | |
mappend x y = x + y + t | |
-- these definitions are trivially commutative | |
-- this obeys the associativity laws: | |
-- first, with nothing equal to 0 | |
-- (x <> y) <> z | |
-- (x + y + t) <> z | |
-- (x + y + t) + z + t | |
-- x + y + z + t + t | |
-- | |
-- x <> (y <> z) | |
-- x <> (y + z + t) | |
-- x + (y + z + t) + t | |
-- x + y + z + t + t | |
-- | |
-- now, with one zero | |
-- (0 <> x) <> y | |
-- x <> y | |
-- x + y + t | |
-- | |
-- trivially equal to (x <> 0) <> y by commutativity | |
-- | |
-- 0 <> (x <> y) | |
-- x <> y directly from our definition | |
-- x + y + t | |
-- | |
-- trivially equal to (x <> y) <> 0 by commutativity | |
-- | |
-- now with two zeros | |
-- | |
-- (0 <> x) <> 0 | |
-- x <> 0 | |
-- x | |
-- | |
-- trivially equal to (x <> 0) <> 0, 0 <> (0 <> x), 0 <> (x <> 0), etc. | |
-- | |
-- three zeros is trivial, any order of operations gives 0 | |
identityLaws :: Troll -> Bool | |
identityLaws x = x <> mempty == x && mempty <> x == x | |
associativityLaws :: Troll -> Troll -> Troll -> Bool | |
associativityLaws x y z = (x <> y) <> z == x <> (y <> z) | |
main :: IO () | |
main = do | |
quickCheck identityLaws | |
quickCheck associativityLaws |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment