A practical introduction to functional programming
maryrosecook.com
maryrosecook.com
This. So much this. I'd go even further and say functional programming is just like imperative programming but without variables (except for those passed in as arguments). This has always struck me as the key difference between the two. The rest (first class / higher order functions, mapping, reducing, pipelining, recursing, currying etc) in my opinion is just making things more convenient in functional languages, dealing with this absence of variables.
The key achievement of functional programming in my opinion is then the provision of special tools (see above) that help programmers solve particular problems in particular efficient ways, that programmers would have solved by using variables in a possibly less efficient way in an imperative language. In short functional programming forces the user to pick the right tool for the task.
"Functional programming is the creation of useful programs using only functions mapping input arguments (perhaps themselves functions!) to outputs (also perhaps functions!) without external state."
You can't leave out the function part of functional programming.
Higher-order functions are a simple and powerful form of abstraction, but not much else. I could imagine something which has the software engineering benefits of an FP language without HOF, although maybe it wouldn't culturally be one.
I think getting enthusiastic about higher-order functions and trying to use them in OO languages can range from good to neutral to bad. On the plus side, code is usually shorter. On the negative side, it's not necessarily more readable, and types still usually expose the same amount of information about their inputs/outputs, which is "call me, anything can happen" (plus plenty of opportunity for lazy side effects, the most confusing kind).
There is something, "ML-alike FP" or, even, "Haskell-alike FP" which I might call "pure FP" which is what you say. This is less difficult to see as being centralized on purity more than "FP" at large. Presumably, you could have "pure" OO, classes and all, by eschewing effects just the same.
I have at least one bet in the pot that you cannot, though. I think the true beating heart of "pure FP"/"Haskell-alike FP" is the centricity of composition as a guiding design of language. This comes directly from some of the category theoretic heritage of the core languages here. Once you're here, the primality of functions themselves is hard to escape from. You can go a ways without HOFs, but the lack of richness of composition which you're stuck with is very painful. BiCCCs are a very sweet spot.
Sure we can simulate these concepts in imperative languages, but the broken abstractions break down rather quickly since the laws are ignored.
Really, I just want to sidestep the argument that is appearing all over this post: that "FP" is also this, and this, and this.
Sure. FP is terrifically poorly defined. The definition used in the article is rather more specific than what most people would say. But it has merits and should be discussed. Let's just not stumble over naming difficulties to do so.
If you wanted to simulate that, imagine writing in C or C++ or Javascript using only functions, only returning copies of things changed by the function, and never referencing global state.
There's nothing particularly magic about that, other than better testability--it's just really slow and obnoxious imperative code. When you start passing around functions and currying values, though, then you're actually starting to see cool things happening.
The task? Take a list of numbers, and produce a list containing only the squares of those numbers--and only those squares falling between 10 and 50.
var inList = [1,2,3,4,5,6,7,8,9,10];
var non_fp = function ( myListOfNumbers ) {
var out = [];
var temp = [];
var i = 0;
var j = 0;
// square the numbers
for (i = 0; i < myListOfNumbers.length; i++) {
temp.push( myListOfNumbers[i] * myListOfNumbers[i] );
}
for (j = 0; j < temp.length; j++) {
if ( temp[j] > 10 && temp[j] < 100 ) {
out.push( temp[j] );
}
}
return out;
}
var fp = function ( myListOfNumbers ) {
return myListOfNumbers.map( function (x) { return x*x; } )
.filter( function (x) { return (x > 10) && (x< 100); });
}
The first has no side effects.The second version has no side effects, and wouldn't be possible without first-class functions, and to me is clearly the more functional answer.
var inList = [1,2,3,4,5,6,7,8,9,10];
var non_fp = function ( myListOfNumbers ) {
var out = [];
// square the numbers
for (var i = 0; i < myListOfNumbers.length; i++) {
var x = myListOfNumbers[i] * myListOfNumbers[i];
if (x > 10 && x < 100) {
out.push( x );
}
}
return out;
}You see the point I'm driving at, though?
(and thanks for prodding me into writing code to illustrate things better)
Yes, absolutely. I thought you were right on the money with the words but I figured a bit of code would do wonders to hammer it down.
Erlang does an even better job I think:
[X * X || X <- lists:seq(1,10), X * X > 10, X * X < 100].
Or: [Y || Y <- [X * X || X <- lists:seq(1,10)], Y > 10, Y < 100].
Slightly longer, but without that X * X repetition.I'm think of Haskell, OCaml or (AFAIK) Erlang. From what I read, Clojure has also a lot of emphasis on immutability.
Both clojure and haskell have mutability, just at differing granularities (haskell monads, clojure replace the world object). They can do it with referential transparency though (which is probably your meaning, obviously pure immutability is impossible and not sensical).
> Both clojure and haskell have mutability, just at differing granularities (haskell monads, clojure replace the world object). They can do it with referential transparency though (which is probably your meaning, obviously pure immutability is impossible and not sensical).
Well, you have to have to be able to manipulate state somehow (even if, at least on the surface, the state monad emulates mutability, as opposed to, eg, OCaml's notion of mutation, which is very explicit in what it does). But the point is that it is not the path of least resistance in these languages.
What C# lacks for me in FP, case matching, has little to do with purity. The FP story involves purity but is not dominated by it. List comprehensions still work in C# even though you can theoretically side effect in your select and filter functions.
I would argue that the lisps are not very functional languages (both in the importance of effects and the style of code I've seen written in lisps), but Scala provides for a lot of FP assurances (val over var, good FP-y libs), and people in the community value effectlessness. So I'm comfortable calling Scala a FP language.
Agda and Idris as well.
The bar for what constitutes "FP" has been changing since the 50s. Doesn't sound unreasonable to me.
So that is Lisp, the first FP in the 60s, and then the MLs of the 70s/80s. They knew about purity, and even preferred it (for things like list comprehensions, it is very useful), but were never very dogmatic about it.
To eliminate print is much harder.
IO was originally handled in Haskell as `main :: [String] -> [String]`. More generally, we might think `main :: [Input] -> [Command]`. This is obviously a pure function. If the types Input and Command are a bit like
Input = SawChar Char | Tick UTCTime | FileRecv String
Command = PrintChar Char | RequestTime | RequestFile FilePath
you can imagine how a more general effects framework could be done purely.In practice, monads are a lot simpler than this. In particular, it can be easy to get desynchronized from your Commands and Inputs.
Other language have more explicit effect typing as well. Conor McBride's `Frank` comes to mind, but it's fairly complex.
I get that this isn't a guide for using functional programming in python, but rather a guide for using functional programming in non-python languages, shown with examples in python. But practically, who's the audience for that?
This article was perfect for me. The "guide rope" paragraph instantly clarified and put into context all the other disjoint pieces of information that I had picked up.
I can now see how to apply these concepts in almost any language. Right away, I can see how to refactor my side-effect-riddled C++ to make it more suitable for unit tests.
I came across this piece after following a previous story on HN, and was very tempted to post it at the time, because it really helped me.
> I know python quite well, but I did not understand functional programming before I read this article
Sounds like someone who would have benefitted from practical uses of FP in python, such as comprehensions.
...It's a really neat article, but I think it would have been considerably improved with asides for "And here's an even cleaner way to write this, if you're using python"
Your suggestion for asides is certainly valid, and I agree would make it more useful for budding pythonistas. I just think that her focus was to introduce functional concepts, and python was simply an easy language to make the concepts concrete. I think that it's stretching the scope of the article, and therefore watering down its message, to put any additional focus on specific features of the python language.
I guess this is an example of my earlier point: I knew about map and reduce, and understood their power. However, it had not clicked for me before reading this article that they feature so prominently in functional programming because they work with functions that have no side effects.
If I was going to claim it was perverse I would say it is a little perverse to teach FP concepts in a language that doesn't support tail call optimisation. Eventually someone who tries to apply this rigorously is going to get an unpleasant surprise in Python. But since it is more about explaining principles than language details I would give it a pass on that anyway.
Anybody that would benefit from re-using some of the lessons from functional programming such as side-effect free programming, splitting pure and stateful code and so on (though some of the examples could do this better than they do now it is a step in the right direction).
Python, PHP, Java, Ruby and C programmers could learn quite a bit from this.
Insofar as python is essentially pseudocode, I can get the appeal of writing non-pythonic python, but ... it strains it a bit to do this for such extensive use of lambda, the most awkward bit of syntax in python, one that almost always has more readable alternatives.
I do like that the author used Python, even if it was only for the purpose of pseudocode. Python is, after all, "executable pseudocode". It's also the only language I really know in-depth.
That said, I agree that it would have been helpful to at least give a mention to list/generator comprehensions.
- braces denote function bodies, even if you don't code it's pretty obvious.
- no strange difference between lambda and def, a function is a function