26

Is there a naming convention for higher order functions? That is, functions which return other functions.

An example in Javascript:

function onlyDivisibleBy(div) { // <-- higher order function
  return function (n) {
    return n % div === 0;
  }
}

var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

arr.filter(onlyDivisibleBy(3)); // [0, 3, 6, 9]
arr.filter(onlyDivisibleBy(5)); // [0, 5]

I've tended to write it as above: that is, optimising for legibility at the invocation point (I'd read the last lines above as "filter the array to get items only divisible by 5"), however at the definition point away from the context in which it's used, it's not so easy to understand what this function does from its name.

3
  • 4
    That's surprising, I'd always understood the term "higher order function" to mean a function which accepted another function as an argument. I'm not saying you're wrong, I just find the difference in our understanding interesting.
    – Racheet
    Commented Nov 20, 2013 at 17:46
  • 7
    @Racheet functions which return functions are also higher order. They may do both.
    – itsbruce
    Commented Nov 20, 2013 at 17:49
  • 3
    @Racheet that's a good point and quite relevant to this example: what the OP is really implementing is partial application. Many (all? not sure) uses where functions are returned can be viewed instead as partial application. @ nickf: here's a cleaner way to implement your example
    – user39685
    Commented Nov 20, 2013 at 19:50

3 Answers 3

17

No, I don't think you need a special naming convention to indicate you are returning a function. As we can see from languages where functions are curried, returning a function is essentially the same as having a function with multiple arguments. e.g. there is little difference between onlyDivisibleBy(3)(6) and onlyDivisibleBy(3,6)

I would change the name from onlyDivisibleBy to isDivisibleBy though as I think is is a more common way to indicate a predicate and onlyDivisibleBy(3)(6) seems odd to return true given that 6 clearly also is divisible by 2

8

In strongly typed functional languages, it is obvious from the function signature what is a higher-order function and what is not, so there is simply no need.

In other languages, I've never come across such a naming convention and I can't think of one which wouldn't just be cumbersome. Better to concentrate on naming functions well than to overload the names like that, I think.

6

No, and you should not use any.

Why?

Because that would be a kind of Hungarian notation. The idea is exactly that functions passed to higher-order functions are just a kind of variables. So treat them like that.

4

Not the answer you're looking for? Browse other questions tagged or ask your own question.