Can Haskell's monads be thought of as using and returning a hidden state parameter?

Posted by AJM on Stack Overflow See other posts from Stack Overflow or by AJM
Published on 2010-05-11T22:53:40Z Indexed on 2010/05/12 0:04 UTC
Read the original article Hit count: 197

Filed under:
|
|

I don't understand the exact algebra and theory behind Haskell's monads. However, when I think about functional programming in general I get the impression that state would be modelled by taking an initial state and generating a copy of it to represent the next state. This is like when one list is appended to another; neither list gets modified, but a third list is created and returned.

Is it therefore valid to think of monadic operations as implicitly taking an initial state object as a parameter and implicitly returning a final state object? These state objects would be hidden so that the programmer doesn't have to worry about them and to control how they gets accessed. So, the programmer would not try to copy the object representing the IO stream as it was ten minutes ago.

In other words, if we have this code:

main = do
    putStrLn "Enter your name:"
    name <- getLine
    putStrLn ( "Hello " ++ name )

...is it OK to think of the IO monad and the "do" syntax as representing this style of code?

putStrLn :: IOState -> String -> IOState
getLine :: IOState -> (IOState, String)
main :: IOState -> IOState

-- main returns an IOState we can call "state3"
main state0 = putStrLn state2 ("Hello " ++ name)
    where (state2, name) = getLine state1
        state1 = putStrLn state0 "Enter your name:"

© Stack Overflow or respective owner

Related posts about haskell

Related posts about monads