Skip to content

Instantly share code, notes, and snippets.

@jmikkola
Last active August 20, 2016 20:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmikkola/7759388d2dfd3eef319160c288b585c5 to your computer and use it in GitHub Desktop.
Save jmikkola/7759388d2dfd3eef319160c288b585c5 to your computer and use it in GitHub Desktop.
-- 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