[Haskell-cafe] Monadic function purity

Brent Yorgey byorgey at seas.upenn.edu
Thu Nov 25 16:11:26 CET 2010

On Wed, Nov 24, 2010 at 12:46:22PM -0800, Gregory Propf wrote:

> I have a pretty basic question.  I've been wondering about whether
> monadic functions that do NOT us IO can be pure or not.  There seems
> to be some confusion on this topic on the web.  I'm especially
> interested in whether they can be memoized.  It seems to me that
> something like a function in the State monad should be pure provided
> the same initial state and same function arguments are present. 
> Likewise with the list monad and most other monads in fact.

The confusion stems from the fact that there are two points of view
from which to look at any monad.  From the point of view of
*implementation*, all Haskell monads other than IO are completely
pure: after all, they are just plain old Haskell code.  For example,
the State monad is implemented as a function that takes an old state
and returns a computed value and a new state.  No tricks, no mutation,
just plain functions and parameter passing.

>From the point of view of *using* a monad, code written using some
monads may *look like* it is impure.  For example, the State monad's
'put' sure looks a lot like mutating a reference cell.  And that's the
point; the State monad lets us think and program as if we are really
mutating a reference cell. But of course under the hood nothing of the
sort is really happening.  It's the same with every monad: each one
models some sort of "effect" in a pure way.

So, the purity of code using monads depends on your point of view.  If
you're worried about whether your code is going to send messages over
the network or give different answers when called multiple times with
the same inputs, the answer is no.  If you're worried about
composability and reasoning about your programs, then you should worry
about extensive use of (say) the state monad for the same reason that
you should avoid global variables in an imperative language.


More information about the Haskell-Cafe mailing list