Assignment versus binding

Gregory Ewing greg.ewing at canterbury.ac.nz
Thu Oct 6 05:10:02 EDT 2016


Ben Bacarisse wrote:
> import Control.Concurrent
> 
> spam io = do x <- io;
>              print x;
>              print (x+1)
> 
> main = spam (do threadDelay (2*10^6); return 1)
> 
> It matches the Python in that the delay happens once.  To get the
> behaviour being hinted at (two delays) you need to re-bind the IO
> action:
> 
> spam io = do x <- io;
>              print x;
>              x <- io;
>              print (x+1)

Yep. What's actually happening here is that spam is being
passed a function, and that function takes an extra implicit
argument representing "the state of the world".

The 'x <- io' part is syntactic sugar for something that
calls io with the current state of the world, and then
evaluates all the stuff after the semicolon with the new
state of the world.

So the first version only evaluates io once, and the second
one evaluates it twice with different arguments (the
states of the world at two different times).

(At least *conceptually* that's what happens. The Haskell
interpreter probably doesn't actually carry the state of the
whole world around inside it. :-)

-- 
Greg



More information about the Python-list mailing list