2 ms·
In the end, there is always some kind of side effect. The value that functional programming adds is you keep the part of the program that does the side effect i
by TheZenPsycho 13y ago
In the end, there is always some kind of side effect. The value that functional programming adds is you keep the part of the program that does the side effect in one spot, doing one specific well defined thoroughly debugged thing and you limit its scope so it can't screw up the rest of your program's operation no matter how bad it goes wrong. It only goes "out". it doesn't cause any side effect inside your program.
One example of a way to structure a functional program is categorising functions according to whether they are a "source" a "filter" or a "sink", (terms stolen from circuit design). The source being your inputs (not pure), filters doing some transformation on the input, over time (pure) and handing off to a sink that causes some side effect (not pure).
In the "real world" You've probably made a lot of simple programs that mostly follow this structure if you've used unix pipes.
If you go along with this, you find that once you start making more sophisticated programs, you need some kind of "memory" so you can progress. Strictly speaking, memory, as we typically use it in imperative languages, is a kind of side effect. In the model above, though, you can make a special kind of "source" which is something like a feedback loop- a source that contains the output of the previous iteration of the program- or some sub portion of the program. Then maintaining a memory becomes a process of continually taking some input, transforming it, creating an output, and then using that output as an input again. (what you might call recursion)
Why would you do this?
Because each part of a program like this is self contained, and its ability to do damage to some distant part of a program is extremely limited. It becomes much easier to reason about such a program. When you find a bug (and these are still possible) you can trace the origin from output to source, or source to output. There is no possibility of some phantom distant subroutine screwing up the dataflow.
And this kind of structure is very useful for games, interactive multimedia programs, and other such graphical interactive program.
A commonly cited "real world" example is xmonad. What I find more insightful is this article on replicating pacman in a functional language.
http://prog21.dadgum.com/23.html http://prog21.dadgum.com/23.html