Skip to content

Instantly share code, notes, and snippets.

@yihuang
Created August 6, 2012 14:55
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yihuang/3275009 to your computer and use it in GitHub Desktop.
Save yihuang/3275009 to your computer and use it in GitHub Desktop.
observer pattern in haskell
{-# 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
@skyscribe
Copy link

Excellent example and awesome!

@meetlai
Copy link

meetlai commented Aug 11, 2012

小伙,代码写得不错.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment