Created
August 6, 2012 14:55
-
-
Save yihuang/3275009 to your computer and use it in GitHub Desktop.
observer pattern in haskell
This file contains hidden or 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 qualified Data.IntMap as M | |
import Data.IORef | |
import Data.Unique | |
{-- | |
- listen :: Event a -> (a -> IO ()) -> IO () | |
- fire :: Event a -> a -> IO () | |
-} | |
data Event a = Event { listen :: (a -> IO ()) -> IO () | |
, fire :: a -> IO () | |
} | |
newEvent :: IO (Event a) | |
newEvent = do | |
handlers <- newIORef M.empty | |
let listen' fn = do | |
key <- fmap hashUnique newUnique | |
modifyIORef handlers $ M.insert key fn | |
fire' a = | |
readIORef handlers >>= mapM_ ($ a) . M.elems | |
return $ Event listen' fire' | |
-- test | |
main :: IO () | |
main = do | |
(e1::Event Int) <- newEvent | |
(e2::Event String) <- newEvent | |
listen e1 (fire e2 . show . (+1)) | |
listen e2 putStrLn | |
fire e1 1 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Excellent example and awesome!