Assignment in most other languages could be thought of as a stateful computation. For instance, when we do x = 5 in an imperative language, it will usually assign the value 5 to the variable x and it will also have the value 5 as an expression. If you look at that functionally, you could look at it as a function that takes a state (that is, all the variables that have been assigned previously) and returns a result (in this case 5) and a new state, which would be all the previous variable mappings plus the newly assigned variable.
Last active
December 20, 2015 14:29
-
-
Save phylake/6147208 to your computer and use it in GitHub Desktop.
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
module Main where | |
main = do | |
t <- runState comp 1 | |
putStrLn $ show t | |
comp :: State Int IO Int | |
comp = put 2 >> get | |
put :: (Monad m) => s -> State s m () | |
put s = State $ \_ -> return ((), s) | |
get :: (Monad m) => State s m s | |
get = State $ \s -> return (s, s) | |
newtype State s m a = State { runState :: s -> m (a, s) } | |
instance (Monad m) => Monad (State s m) where | |
return a = State $ \s -> return (a, s) | |
-- t = \s -> (a, s) | |
-- f = a -> (\s -> (a, s)) | |
State t >>= f = State $ | |
\initState -> do | |
(a, s) <- t initState | |
let State newState = f a | |
newState s |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment