Hacker Read top | best | new | newcomments | leaders | about | bookmarklet login
How to get started with functional programming (www.johndcook.com) similar stories update story
60.0 points by wglb | karma 64679 | avg karma 7.38 2011-07-25 03:51:24+00:00 | hide | past | favorite | 43 comments



view as:

I maintain that the best way to get started with functional programming is to pick a functional language and try to write a program with it.

Exactly this.

Trying to write pure functions in a standard language is completely the wrong approach. You might as well say, tie one hand behind your back and try to write with the other hand.

Many functional languages don't require pure functions.

Many functional languages have garbage collectors, and they are fundamental for writing pure functional data structures. (It's almost impossible to properly emulate this in, say C, especially if your structures have cycles)

Many functional languages have other great features like type inference, macros, data patterns and more. Just using an existing language won't give you any taste for these.


> Many functional languages don't require pure functions.

Yes. Though I would suggest a newcomer to pick a language that requires purity, in order to make the transition cleaner.


The point is not: how. The point is: why.

There are plenty of resources on why you would want to program functionally.

One of the most notable one is:

http://www.cs.utexas.edu/~shmat/courses/cs345/whyfp.pdf

Benefits include: Easier reasoning about code correctness. More powerful abstractions leading to clearer and more succint code. Easier mechanical refactoring of code. Easier parallelism. More powerful compiler optimizations.


Great, now answer: why not.

Depends on what you are looking for.

Apart from any benefit from actually using any language or tool, there's also the joy of learning.


I would finesse that slightly and say that the way is to pick a multi-paradigm language (OCaml, Scala, etc) and gradually work in more FP as you get more comfortable with it. E.g. you can start gently by simply replacing for loops with maps or folds, then introduce HOFs/closures, etc etc.

I do like the idea of functional programming as a paradigm - that can be used in any language - and dodged when needed - much better than pure functional programming/languages. As a game designer, with so many state-dependent parts, and with so many refactoring iterations that come along with designing a game from the ground up, too much functional code would become a burden. The approach suggested here on the other hand - trying using to use FP as much as reasonable - allows me to benefit with FP when possible while maintaing agility.

In a language like c++, what would be an elegant naming convention to differentiate between pure functions and others?


This is definitely coming from someone who has never written a stateful functional program. You have to write things pretty differently but it’s usually better than it’s imperative counterpart. It works just fine, trust me.

You may be interested in James Hague's "Purely Functional Retrogames" (http://prog21.dadgum.com/23.html) series of posts. He's written several about the hurdles and benefits of using FP for game programming. (He's using Erlang.)

He basically seems to have come to the conclusion (even moreso in more recent posts) that functional languages are not the way to go, so I'm not sure it's the best starting point unless that's where you want to end up.

Not really - he's very positive about Erlang, for example. He thinks that going for absolute functional purity is not worth the effort, but that mostly functional (or functional-by-default) is very practical. I tend to agree.

His criticism is pretty fair, too - far more substance than a dozen "oh wow, look at how small quicksort / fibonacci is" blog posts.


I've read some of James Hague's more recent posts on FP, and I got the same idea from them than @radarsat1. But more importantly, until I see someone adopting FP for the game logic in a innovative game - re-writing Pacman doesn't have the challenges of programming something while inventing it - and concluding that it is beneficial, more productive game design with FP is an unproven idea. See @eru's answer with the Tim Sweeney talk.

> In a language like c++, what would be an elegant naming convention to differentiate between pure functions and others?

D is a bit like C++. And its type system supports pure functions. I don't know if there's a standard naming convention, but D is worth a look.


You might be interested in the talk "The Next Mainstream Programming Language: A Game Developer’s Perspective" [0]. The authors argue that functional programming is the future of game programming.

[0] http://www.st.cs.uni-saarland.de/edu/seminare/2005/advanced-...


Good read, thanks. But in practice, with all its problems, C++ has been proven to work over and over, and the author's - Tim Sweeney - work is proof of that. Today, 6 years after this talk, has anyone successfully made a commercial game with the game logic built with FP, and if so, was it more productive than the former approach? I'm not saying the lack of examples prove it's not beneficial, but believing it is, is still only a guess.

FP languages in games:

- Jax and Daxter (and Crash Bandicoot): http://ynniv.com/blog/2005/12/lisp-in-games-naughty-dogs-jax... - Abuse: http://en.wikipedia.org/wiki/Abuse_(computer_game) - Lua (even though it is not strictly functional) is used quite a bit throughout the game industry.


Of those examples only Jak and Dexter is actually about functional programming in game dev. It's a good example though. But the outcome of using FP didn't turn out that great for them, it did not make them more productive:

A single programmer (who could easily be one of the top ten Lisp programmers in the world) wrote GOAL. While he called his Lisp techniques and programming practices "revolutionary," others referred to them as "code encryption," since only he could understand them.

So we found one example, and it didn't prove FP is beneficial to productivity.


You are right, we need to see more examples of functional programming being used in games. Then we can better tell what effects it has.

Interestingly, you can also say that Cobol has been proven to work for business applications over and over. And people build successful websites with PHP.


How to get started with functional programming? How to get started with programming? How to get started with anything?

Just start doing it, do some research for stuff you don't understand, and see if it flies for you.

I'm not an elitist although I might very well come out as one but any article with a title analogous to what's above is by definition missing the target. My reasoning goes that anyone who's worth his salt and interested in functional programming has got, or will get, started with it without any such an article. Anyone who's either not worth his salt or not interested in it will not start functional programming or programming or anything because of some article (or a few of them). In general, of course.


Just staying in your language is a very bad idea. The problem is that if your language and your librarys don't support FP very well you will have a very hard time. Even somebody that knows FP very well will have problems applying FP in a Java setting. Its surly possible but you will have a hard time.

Its better to start with a language that helps you do the right thing. Additionally if you do FP in Java or C++ you will not get all the benefits and after you tried it conclude that FP is not worth it.

Start with Haskell, ML, Clojure or something like that.


To the contrary. From my experience adding FP to Java is something natural, good devs do this on their own without wanting to write FP code. Side effect free methods, immutable objects, immutable data structure etc. all add to better code in large code bases. That's why good devs use Google Guava or LambdaJ instead of for loops for example.

Do you use any naming convention to differentiate between pure and non-pure functions?

No. I wish there was an IO monad (an exception monad) in Java. Or at least a common understanding in compilers and IDEs about a @Pure annotation.

That could be right i don't know and I haven't heard of Google Guava or LambdaJ. I know that Uncle Bob for example say that methodes with no arguments are best and that the opposit of what FP is all about (there are other examples like this).

So, are you arguing that good java devs don't follow the standart java comunity idioms?

Sure there are some devs that to that but to say FP is natural to any good Java dev is a bit of a stratch.


Can you link me to the Uncle Bob article?

I think it was this video but im not 100% sure. http://www.viddler.com/explore/oredev/videos/15/

Never heard of that "no arguments are best" java community idiom in the last 15 years, so can't comment on that.

> Start with Haskell, ML, Clojure or something like that.

Just make it Haskell. If you want to learn FP, you cannot do better than Haskell. Of course if you want to write apps tomorrow Clojure is a pretty good choice.


I agree that Clojure is not the best to start but if you take ML (OCaml) or Haskell does not really matter. Haskell has intressting typeclasses but that it is lazy is something that you might not want to learn (if you just want to learn the value of FP).

Clean might also be worth a look. But it guess for a beginner the slight differences do not really matter that much.

I recommend Haskell over OCaml for learning. Haskell has a cleaner syntax, a living community, and emphasises purity.


You do not need to start with functional programming, because if you're good, the probability is high you already do it (at least the Java devs I know do it).

This means immutable data structures, writing for composability, side effect free methods, list processing with "closures" instead of for loops etc.


The majority of the population of the world doesn’t know how to do functional programming, so there’s a pretty big audience for whom this article is applicable.

Spreadsheets are a limited form of functional programming.

I'm very skeptical that "good Java devs" tend to use FP techniques.

Idiomatic Java is object-oriented, and OO is inherently stateful: side-effects are everywhere and are totally acceptable. Also, it tends to use iteration rather than recursion, doesn't use higher-order functions, classes and methods are designed for "inheritability" rather than composability. However, I'd love to be proved wrong. Care to show any open-source Java code that uses FP techniques?


I think you mix things. FP has nothing to do with stateless. Languages all have nothing to do with statelessness or statefulness, this is an application architecture term.

Objects have state, as have immutable data structures.

"doesn't use higher-order functions,"

But they use higher-order objects.

"classes and methods are designed for "inheritability"

No, at least for 10 years it has been debunked in Java that inheritance is a good thing. Inheritance outside of some small domains like GUI libraries is a bad thing as inheritance is too rigid. Most bad Java developers use inheritance because they've been teached OO in a completly wrong way with dogs and cats or cars and trucks.

I think the common understanding for years in Java/C# etc. is that composition is much better than inheritance.

This article from 1998 describes the problem of inheritance vs. composition in java

http://www.artima.com/designtechniques/compoinhP.html

"Care to show any open-source Java code that uses FP techniques?"

No, because to be frank, I have not much knowledge about Java open source. And the projects I've looked into (Apache comes to mind) have sub-industry quality or are outright awful. Not sure why this is the case though.


Trying to use a pure functional style inside an imperative environment will just give you the idea that it is a horrible programming style.

Pure functional programming is a different enough approach that it requires a whole different eco-system of libraries. Differently-optimizing compilers, to avoid large runtime penalties. And a different mindset.

I think the author is talking about acquiring the different mindset, but in a setting where it is just not very practical.


One of these days I wanted to try writing a C++ program in a totally immutable style, just to see how far you can take that concept. E.g. all classes have const members. The only way to mutate the instance is to pass its members to a constructor for a new one. Using smart pointers this shouldn't cause too much memory-handling overhead. Function objects for higher-level functions. You'd almost get a functional OOP language. But it might be hard to stick with it. I'm not sure it would produce very fast code however, doing allocation and deallocation all the time. Maybe if it was combined with a smart allocator that could reuse discarded objects.

Functional languages only get away with immutability, because they give you better tools for combining parts of your program. For example, higher order functions.

I believe that you can write a totally immutable C++ program. But it's probably much harder than writing the same program in Haskell. You could try writing an immutable program in D. D is somewhat similar to C++, but much saner.


Legal | privacy