Skip to content

Instantly share code, notes, and snippets.

@robstewart57
Last active December 14, 2015 11:39
Show Gist options
  • Save robstewart57/5081126 to your computer and use it in GitHub Desktop.
Save robstewart57/5081126 to your computer and use it in GitHub Desktop.
Haskell type class with state
{-# 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