Last active
December 14, 2015 11:39
-
-
Save robstewart57/5081126 to your computer and use it in GitHub Desktop.
Haskell type class with state
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 ScopedTypeVariables #-} | |
import Control.Concurrent.MVar | |
class Foo a where | |
mkFoo :: IO a | |
readFoo :: a -> IO Int | |
operateOnFoo :: a -> IO () | |
newtype Bar = Bar (MVar Int) | |
newtype Baz = Baz (MVar Int) | |
instance Foo Bar where | |
mkFoo = newMVar 0 >>= \i -> return $ Bar i | |
readFoo (Bar mv) = readMVar mv | |
operateOnFoo (Bar mv) = | |
modifyMVar_ mv $ \i -> return (i+1) | |
instance Foo Baz where | |
mkFoo = newMVar 10 >>= \i -> return $ Baz i | |
readFoo (Baz mv) = readMVar mv | |
operateOnFoo (Baz mv) = | |
modifyMVar_ mv $ \i -> return (i*2) | |
mkBar :: IO Bar | |
mkBar = mkFoo | |
test1 :: IO () | |
test1 = do | |
bar <- mkBar -- i=0 | |
operateOnFoo bar -- i=1 | |
operateOnFoo bar -- i=2 | |
i <- readFoo bar | |
print i -- prints 2 | |
mkBaz :: IO Baz | |
mkBaz = mkFoo | |
test2 :: IO () | |
test2 = do | |
baz <- mkBaz -- i=10 | |
operateOnFoo baz -- i=20 | |
operateOnFoo baz -- i=40 | |
i <- readFoo baz | |
print i -- prints 40 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment