[Haskell-cafe] Execution order in IO

Andrew Butterfield Andrew.Butterfield at scss.tcd.ie
Wed Apr 15 13:51:21 UTC 2015


Hi Jon,
> On 15 Apr 2015, at 14:26, Jon Schneider <haskell at jschneider.net> wrote:
> 
> Perhaps I need to be more specific.
> 
> main = do
> a <- getLine
> b <- getLine
> 
> Can we say "a" absolutely always receives the first line of input and if
> so what makes this the case rather than "b" receiving it ? Or do things
> need to be slightly more complicated to achieve this ?

No, that is the case. The IO monad acts like a state monad under the hood, and getLine changes that "IO state",
to one in which the next line has just been read in. So the contents of 'b' will be line that was read immediately after 
the line read leading to the contents  of 'b'
> 
> Sorry it's just the engineer in me. I think once I've got this clear I'll
> be happy to move on.

I'm an engineer too - know the feeling.

But, imaging a pure function f that does something with strings, and which can fail badly (unhandled runtime exception) if the string is ill-formed.
Now consider

main = do
 c <- fmap f $ getLine
 d <- getLine 
.... something involving c ....

Now, if the first getLine returns an ill-formed string, laziness may mean that the second getLine occurs,
and we see the program crash with a runtime error in the evaluation of c after two getLines.
In effect the evaluation of f is deferred until it is needed in the 3rd line...

Hope this helps!
> 
> Jon
> 
> _______________________________________________
> Haskell-Cafe mailing list
> Haskell-Cafe at haskell.org
> http://mail.haskell.org/cgi-bin/mailman/listinfo/haskell-cafe

Andrew Butterfield
School of Computer Science & Statistics
Trinity College
Dublin 2, Ireland



More information about the Haskell-Cafe mailing list