8 ms·
A practical introduction to functional programming
- bufordsharkley 12y agoSeems somewhat perverse to do this in python, and never once mention list/generator comprehensions. 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?
- jacquesm 12y ago> But practically, who's the audience for that? 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.
- bufordsharkley 12y agoIt's a well-written and nice article, but just kinda weird in spots, saying that the code is more self-evident and readable, whereas I think it's sometimes making a language do something it only does with considerable strain. 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.
- ferrari8608 12y agoAny time I see a use for lambda (typically only with the functional builtins), I just write a function instead. Two extra lines are worth it for the readability alone. You can also reuse a function, which makes more sense to me than potentially writing the same lambda multiple times. 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.
- girvo 12y agoInterestingly, at least at the places I've worked at recently, that functional "style" or kernel of truth is being picked up by more and more PHP programmers. It's great, makes it far easier to test code.
- jgable 12y agoI am. I know python quite well, but I did not understand functional programming before I read this article. Oh sure, I'd looked it up on wikipedia, and read a few blog posts, and perused a Haskell tutorial, but none of that made it click. Too many new concepts at once. Using python as the instructive language is great simply because many people know python, and for those who don't, the syntax is easy to follow. 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.
- bufordsharkley 12y agoIt really is an excellent introduction to FP, but: > 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"
- jgable 12y agoI do know list comprehensions, and I use them all the time (not trying to be defensive here, just providing context). I understand that they are just a different syntax for mapping -- applying a function to members of a list to produce a new list. However, while list comprehensions are clean and pythonic syntax, I think the "map" syntax more clearly illustrates the concept that the author is trying to teach. 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.
- zmmmmm 12y agoI thought leaving out list comprehensions was an excellent idea - it is a construct that few programmers from other languages would understand, and would have caused parts of the article to turn into a python tutorial. As it is, the python is close enough to universal pseudo-code. 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.
- agumonkey 12y agoBecause the purpose is to demonstrate the use of functions. * comprehensions are syntactic sugar above them and would hide their true nature.
- csandreasen 12y agoI can see the value in not using Python's comprehensions because although they provide an easy way to write map and filter, there's no clean, consistent way of expressing fold (or reduce or whatever you want to call it) - at least, not without altering state, which flies in the face of what this tutorial is trying to teach. Since those are the big three, I can see the value of writing everything with lambdas in the tutorial just to keep things consistent. That said, I agree that it would have been helpful to at least give a mention to list/generator comprehensions.
- warkid 12y agoThis would show that with proper language support FP could be much more pleasant. Who would want to try and apply ideas from this worderful article to, say, her everyday C++ coding? After seeing something like squares=[x*x for x in range(10)] she would write exactly WHAT in C++?
- woah 12y agoJS would probably have been a better language for a few reasons: - 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
- rsp1984 12y ago> Ignore all that. Functional code is characterised by one thing: the absence of side effects. It doesn’t rely on data outside the current function, and it doesn’t change data that exists outside the current function. Every other “functional” thing can be derived from this property. 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.
- angersock 12y agoEh, I think that leaving out first-class functions is unforgivable. The complete spirit of functional programming can be neatly summed up as: "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.
- gracenotes 12y agoI would agree with GP that emergent code organization principles that come from eliminating side effects are the crux of FP, as far as being the bottom line of what makes it effective and worth internalizing. 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).
- tel 12y agoIt's worth noting that things like print and random are just as much side effects as mutability. To eliminate random is easy: realize that random generation is a function from a hidden random generator state to a "random" value and a new random generator state. Now use state-minimization techniques. To eliminate print is much harder.
- rubiquity 12y agoprint is IO so of course it is hard to eliminate side effects.
- coolsunglasses 12y agoYes, but you can uncouple the API talking about and generating IO actions from the performance of those IO actions if you have a pure, lazy language.
- tel 12y agoIO monads aren't the only way. If all you want is print it's even quite easy.
- sanderjd 12y agoPlease do tell or link to more, if you're willing!
- tel 12y agoPrint alone is easy as you can just have functions output both their normal output and a listing of whatever they printed. These listings then get concatenated together (this is technically "the writer monad", but you don't need to know as much). 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.
- esaym 12y agoI found Higher Order Perl as a good tutor as well: http://tinyurl.com/orwm2ed http://tinyurl.com/orwm2ed
- bmn_ 12y agohttp://amazon.com/dp/1558607013 http://amazon.com/dp/1558607013
- Tycho 12y agoThe lambda syntax seems like a major shortcoming in Python's readability. It uses the comma in its declaration and then the comma is used again a separator for the arguments being passed into the outer function (reduce in this case). I feel their should be better visual indication for when you are out of the lambda part.
- hueving 12y agoIsn't the colon an adequate indicator that you have left the anonymous function declaration?
- deleted 12y ago[deleted]
- lateguy 12y agoI think the same article was on hacker school website also?
- avinassh 12y agoYes, since the author works at Hacker School.
- scarylettuce 12y agoSo clearly written. Thank you.