runarorama / runarorama.github.com

9 stars 3 forks source link

A Critique of Impure Reason #9

Open runarorama opened 10 years ago

runarorama commented 10 years ago

Comments welcome

lundril commented 12 months ago

No clue if you are still reading this. I am trying to understand functional programming on a fundamental level. So I read your article about "pure" vs "impure". You give this example:

String x = new String("");
String y = new String("");

And argue "... what could it possibly mean for them to not be identical?". Well what's with this example:

Integer x = getInputFromUser();
Integer y = getInputFromUser();

Unfortunately that's about 90% of programs, that I have to work with. So how does that fit into a "pure world"? You could of course argue that getInputFromUser obviously has a side-effect; even if I cannot tell what the side-effect should be. As far as I can tell the "side-effect" is sitting in front of the computer...

runarorama commented 12 months ago

getInputFromUser() is going to have a side effect in the sense that its result is not predictable. x and y will have different values, and the program might in fact throw an error (another side effect) and crash completely if the user enters something invalid. The type Integer for x and y is a complete lie.

In functional programming, we always deal with functions where the result is purely determined by the arguments to the function.

So then how do we get input from the user? Well, in Haskell for example, something like getInputFromUser is not an expression that has the side effect of calling out to the runtime system and asking the user for input. Rather getInputFromUser is just a value exactly like "" and it gets returned to the runtime system as a result.

In a purely functional setting there's always this kind of inversion of control, where instead of calling out to things that have side effects, we expect our functions be called from something that has the ability to perform those effects. We never perform them directly, just return values that delegate to the caller.