Skip to content

Instantly share code, notes, and snippets.

@raichoo
Created October 24, 2011 08:42
Show Gist options
  • Save raichoo/1308609 to your computer and use it in GitHub Desktop.
Save raichoo/1308609 to your computer and use it in GitHub Desktop.
Mixin experiment
import Data.IORef
import Control.Applicative
data CounterRep = CounterRep { x :: IORef Int }
newCounterRep = CounterRep <$> newIORef 0
data Counter = Counter { get :: IO Int,
set :: Int -> IO () }
counterClass = \rep -> Counter { get = readIORef $ x rep,
set = writeIORef (x rep) }
doubleMixin into = \rep -> let super = into rep in
Counter { get = get super,
set = set super . (*2) }
plusOneMixin into = \rep -> let super = into rep in
Counter { get = get super,
set = set super . (+1) }
newCounter = counterClass <$> newCounterRep
newDoubleCounter = doubleMixin counterClass <$> newCounterRep
newDDCounter = (doubleMixin . doubleMixin) counterClass <$> newCounterRep
newDPlusCounter = (plusOneMixin . doubleMixin) counterClass <$> newCounterRep
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment