[Haskell-cafe] Tetris

Laurent Deniau laurent.deniau at cern.ch
Tue Nov 20 12:07:21 EST 2007

Andrew Coppin wrote:
 > 2. How do you implement a program that is fundamentally about state 
mutation in a programming language which abhors state mutation?

Haskell taught me one thing (at least). The World is not mutating but it 
is moving. Physics shows that no movement (no time) means no World (in 
fact it means that you can't know if the World exists or not, which is 
the same).

You can take the (discrete) analogy of a (time) *sequence* of pictures 
which builds a movie. The pictures are immutable and so is the movie, 
but looking quickly at the pictures makes the movie looking like a 
mutable picture. Everything here is about (time) sequence, not mutability.

It is the same about Monad. Monad are not about side effects nor 
mutability, but about sequencing. It uses the principle of causality 
that one need to apply a function to its arguments before it returns a 
result (and encapsulates this behavior in an object). Note that it says 
nothing about lazy or eager evaluation, since the result can be either a 
value or an (lazy) expression which evaluates to the value. What this 
latter expression captures is the sequence of evaluation to perform to 
get the value. Again, everything here is about sequence, not mutability.

Mutability is an (apparent) optimization. Creating a new state from the 
previous state in the (time) sequence has a cost (note the functional 
nature of this transition). Since a big part of this process can be 
shared to reduce this cost, namely creating the storage / structure / 
value / whatever of the state, one can think to reuse as much as 
possible. In the movie analogy, this optimization is called mpeg 
compression which only encodes the changes between images in the 
sequence. The Haskell compiler can also do this kind of optimization as 
soon as it doesn't change the observable behavior of the program. This 
means that a Haskell program can have/deal with mutable states resulting 
from an optimization. This mutability is explicit within the IO Monad 
since it is the standard way to communicate with the computer World.

So the only (required) mutable states in the game are related to the IO, 
not to the game states as one might think. But the encapsulation of 
these states inside some monads may let the compiler do some 
optimization for you.

my 2 cents of Euro.

a+, ld.

More information about the Haskell-Cafe mailing list