Created
August 3, 2013 19:30
-
-
Save ehamberg/6147675 to your computer and use it in GitHub Desktop.
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
| import Prelude hiding (lookup) | |
| import Data.IORef | |
| import Data.Maybe | |
| type NatArray a = IORef (Int -> Maybe a) | |
| newArray :: IO (NatArray a) | |
| newArray = newIORef (const Nothing) | |
| lookup :: NatArray a -> Int -> IO (Maybe a) | |
| lookup a n = readIORef a >>= \f -> return (f n) | |
| update :: NatArray a -> Int -> a -> IO () | |
| update a m v = | |
| readIORef a >>= \oldf -> | |
| writeIORef a (\n -> if n == m then Just v else oldf n) | |
| main = do | |
| a <- newArray :: IO (NatArray String) | |
| lookup a 0 >>= print . isNothing | |
| update a 10 "foo" | |
| update a 20 "bar" | |
| update a 10 "baz" | |
| lookup a 10 >>= print . (==Just "baz") | |
| lookup a 20 >>= print . (==Just "bar") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment