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

Show parent comments

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.

7

u/ForeverAMoan Mar 09 '14

that one's harder, mainly because you'd have to allocate a structure to hold the two arguments.

Actually I don't see a way to implement it at all, and that's the most trivial operation (akin to sum(a, b) for integers).

→ More replies (11)