2 ms·
Pure functional programming's core delusion is pretty clear as well: all state is immutable. There is no "state" in functional programming, there is function a
by jrockway 17y ago
Pure functional programming's core delusion is pretty clear as well: all state is immutable.
There is no "state" in functional programming, there is function application. Your program is a function from some value (inputs) to some value (the result). You write that program by composing various smaller programs with operators like (.) and (>>=) (or if you like being generic, (>>>)). There is no data, there is just function application.
So then, "state" becomes an imaginary concept that sometimes makes things easier to think about; if there is a sequence of computations that logically operate on the same "thing", then you call that "thing" the state. The State monad is nothing but syntax sugar that lets you very explicitly pretend that there is a such thing as state; something you can "get" at and "put" into as needed. This abstraction, BTW, is no different than state in any other language (which is why it comes up so much in hastily-written Haskell programs; you can just cut-n-paste from C and change the spelling of some keywords), except instead of "get" and "put", you just use variable names and "=". Otherwise, exactly the same concept and semantics, and very similar syntax everywhere.
In procedural languages, state is important because the procedures abstract CPU instructions, which operate on little boxes called "registers". But in functional programming, your program is not a list of things to do to a register, it's just functions. So state is not really meaningful anymore. Don't program the machine, program your algorithm!
I've yet to be convinced that Haskell actually gains very much from its stateless-ness; I understand that in principle there are nice optimizations that it can enable, and parallelization becomes rather simple, but I'm not seeing it beat the pants off of impure functional languages in speed or clarity.
http://donsbot.wordpress.com/2010/02/26/fusion-makes-functional-programming-fun/ http://donsbot.wordpress.com/2010/02/26/fusion-makes-functio...
But nothing is ever going to "beat the pants off" hand-optimized assembly in a benchmark; there is only so much work a computer can do, after all. In the real world, however, people don't have time to spend hundreds (or thousands!) of hours optimizing four lines of code. In that case, you'll find that these theoretical optimizations are great -- you write code the natural way, and the optimizer turns that into something closer to the optimized-for-hundreds-of-hours assembly. C and Java compilers just can't do that because it can't make any assumptions about what you mean, it can only work with what you say (since those programming languages are basically high-level lists of instructions for the CPU to perform).