What's Functional Programming All About?
Functional programming makes compilers nicer to work with, because you can tell them explicitly when locality can be assumed.<p>All compilers which do any kind of optimization have to reason about the code as if it were functional. Otherwise, they couldn&#x27;t rearrange mathematical expressions and do things like common subexpression elimination or constant folding or even simple algebraic rearrangements we expect to happen because we, as humans, know that mathematical operators are are functions and therefore side-effect-free and therefore can be switched around arbitrarily as long as the end result is correct, because the end result is all that matters.<p>But a compiler which could only optimize arithmetical and algebraic code would be worthless. How about memory accesses? How about function calls in tight loops? And that&#x27;s where you run into problems in a language like C, where strong assumptions about who gets to look at what generally don&#x27;t hold. Optimizing memory accesses is hard because you don&#x27;t know who&#x27;s looking at the memory in a global sense. Spooky action-at-a-distance crops up, the kinds of things humans don&#x27;t cope with well because the effect could be many pages of code removed from the cause. C has the volatile keyword for some instances of this, which basically kills optimizations for certain variables, but the general problem stands: C is unphysical. Locality cannot be assumed. Humans don&#x27;t deal with that very well.<p>In a language like C, therefore, there&#x27;s a tension between generating optimized code and generating predictable code, and that tension comes from the fact the compiler doesn&#x27;t know which code could have side-effects and, therefore, invoke spooky action-at-a-distance if it&#x27;s optimized too aggressively.<p>In Haskell, or any other language where side-effects must be explicitly marked, that problem goes away. Most code is purely local in its effects, and only special code, written inside a special monad, can invoke nasal demons if the optimizer gets too frisky. The compiler can trace its data-flow graphs and do all kinds of tricks secure in the knowledge that nobody outside can peek in to see how the sausage is being made. Only in special, marked locations do the values get exposed to the outside world, which must be done in an orderly fashion.<p>So all code is potentially functional. Functional languages just make it possible for the developer and the compiler to agree about precisely <i>which</i> code that is.