Created
November 11, 2015 14:12
-
-
Save kc1212/9a035b8baf09c49734f9 to your computer and use it in GitHub Desktop.
Simulating key-value database using StateT
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
import Control.Monad.State | |
import qualified Data.Map as Map | |
type MyMap = Map.Map Int Char | |
runDB :: StateT MyMap IO () | |
runDB = do | |
add 1 'a' | |
add 2 'b' | |
x <- find 1 | |
y <- find 2 | |
z <- find 3 | |
io $ print x | |
io $ print y | |
io $ print z -- shows Nothing | |
return () | |
-- find the value of the key if exists | |
find :: Int -> StateT MyMap IO (Maybe Char) | |
find k = do | |
m <- get | |
io $ print ("getting from disk: " ++ show k) | |
return (Map.lookup k m) | |
-- add some key/value pair to a map | |
add :: Int -> Char -> StateT MyMap IO () | |
add k v = do | |
m <- get | |
put $ Map.insert k v m | |
io $ print ("writing to disk: " ++ show k) | |
return () | |
io :: IO a -> StateT MyMap IO a | |
io = liftIO | |
main :: IO () | |
main = runStateT runDB (Map.empty) >> return () | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment