Python-based monads essay part 2

Chris Angelico rosuav at gmail.com
Wed Oct 19 12:05:08 EDT 2016


On Wed, Oct 19, 2016 at 9:26 AM, Gregory Ewing
<greg.ewing at canterbury.ac.nz> wrote:
> The things being reasoned about -- the actions -- are
> not themselves functions, but that doesn't mean there's
> any cheating going on. Would you say it was cheating
> to perform algebraic manipulations on an expression
> involving numbers or strings? Why should it be any
> different when the things being manipulated represent
> actions that affect the world?

Okay. Let me pick up two of functional programming's favourite idioms,
and you can help me understand how I/O monads fit into them.

1) Lazy evaluation. In an imperative language, you can't say "make me
a list of prime numbers, then take the 73rd element"; but functional
languages are perfectly happy to have an infinite-length as an object,
as long as you never actually ask for the last element or anything.

2) Related to the above: Dead code elimination. If the 73rd prime ends
up being multiplied by zero, Haskell is entirely justified in not
calculating it.

Okay. Now let's suppose that, instead of "73" in the first step, you
have "ask the user for an integer". Are you allowed to eliminate this
prompt, since the result of it cannot possibly affect anything? And if
not, why not? After all, eliminating terms that have been multiplied
by zero is one form of algebra. If numbers and strings and I/O monads
are all the same, there's no difference between "length of this
string" (an operation yielding an integer) and "ask the user for an
integer".

If you consider that the world changes state as a result of asking the
user for input, then you've just eliminated all notion of functional
purity. You have side effects, plain and simple, and you're using
imperative code. At what point can you deem that the algebra is safe?
At what boundary can any of your code manipulations still be done?

ChrisA



More information about the Python-list mailing list