Created
October 24, 2011 08:42
-
-
Save raichoo/1308609 to your computer and use it in GitHub Desktop.
Mixin experiment
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
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