Last active
August 20, 2016 20:27
-
-
Save jmikkola/7759388d2dfd3eef319160c288b585c5 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
-- requires "mtl" | |
import Control.Monad.State | |
import Control.Monad.Except | |
import Data.Map (Map) | |
import qualified Data.Map as Map | |
data Err = Missing String | OtherErr | |
deriving (Eq, Show) | |
type Stored = Map String Int | |
type StoreM = StateT Stored (Either Err) | |
note :: a -> Maybe b -> Either a b | |
note msg = maybe (Left msg) Right | |
save :: String -> Int -> StoreM () | |
save k v = modify (Map.insert k v) | |
load :: String -> StoreM Int | |
load k = do | |
store <- get | |
lift $ note (Missing k) (Map.lookup k store) | |
stateManip :: StoreM Int | |
stateManip = do | |
save "x" 1 | |
save "x" 2 | |
save "y" 123 | |
x <- load "x" | |
y <- load "y" | |
save "z" (x + y) | |
load "z" | |
main = putStrLn $ show $ evalStateT stateManip Map.empty |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment