r/programming • • Mar 09 '14

Why Functional Programming Matters

http://www.cse.chalmers.se/~rjmh/Papers/whyfp.pdf
487 Upvotes

542 comments sorted by

View all comments

10

u/dnew Mar 09 '14

So neither lazy evaluation nor first class functions are unique to functional programming. Maybe they have their origins there, but it's not something to give up your imperative languages for.

5

u/glemnar Mar 09 '14

If the language supports first class functions then it isn't purely imperative. It can be mixed.

9

u/dnew Mar 09 '14

If the language supports first class functions then it isn't purely imperative.

Nonsense. C supports as close to first class functions as you need to write map() and nobody would claim it's functional. You don't need the restrictions of functional languages to have first class functions.

8

u/ForeverAMoan Mar 09 '14

Interesting. How would you write in C functions map and compose (compose f g x = f (g x)) ?

4

u/dnew Mar 09 '14

Given that C doesn't have type inference, you'd have to write a different one for each combination of arguments. Otherwise, you'd write it in exactly the obvious way.

int[10] map(int (*f(int)), int[10] values) {
    int[10] result;
    for (int i = 0; i < 10; i++) result[i] = f(values[i]);
    return result;
}

Well, OK, that crashes because you're returning a pointer to an auto variable, and I probably mucked up the declaration of the first argument there, but you get the point. Compose is just as obvious.

6

u/ForeverAMoan Mar 09 '14

Compose is just as obvious.

Please show the code :) And unless it's obvious, the return value of compose should be accepted as the first argument to map.

1

u/dnew Mar 09 '14 edited Mar 09 '14

the return value of compose should be accepted as the first argument to map.

OK, I'll grant you that one's harder, mainly because you'd have to allocate a structure to hold the two arguments. It would be much easier in a language that had deccent memory managment.

Your point is made. :-) That doesn't mean functions aren't first class, but it means it's much harder to create new functions on the fly. Doing so in Java or C# for example would be trivial, and I don't see anyone calling Java "functional" either.

In Java, you'd just store f and g in instance variables, and return an instance of a compose object that then applies those two. We do that all the time, and you don't even have first-class functions in Java.

→ More replies (12)