My two primary languages, Java and Ruby, don’t have explicit support for HOFs, but they both have some related functionality.
Let’s first look at Wikipedia’s definition of Higher Order Functions:
In mathematics and computer science, higher-order functions are functions which do at least one of the following:
- take one or more functions as an input
- output a function
The map function found in many functional programming languages is one example of a higher-order function. It takes a function f as an argument, and returns a new function which takes a list and applies the f to each element.
Ruby supports a HOF-like mechanism through the yield keyword. Here’s a snippet from the Bill Venners/Matz interview on Artima:
Bill Venners: Ruby supports blocks and closures. What are blocks and closures, and how are they used?
Yukihiro Matsumoto: Blocks are basically nameless functions. You may be familiar with the lambda from other languages like Lisp or Python. Basically, you can pass a nameless function to another function, and then that function can invoke the passed-in nameless function. For example, a function could perform iteration by passing one item at a time to the nameless function. This is a common style, called higher order function style, among languages that can handle functions as first class objects. Lisp does it. Python does it .Even C does it with function pointers. Many other languages do this style of programming. In Ruby, the difference is mainly a different kind of syntax for higher order functions. In other languages, you have to specify explicitly that a function can accept another function as an argument. But in Ruby, any method can be called with a block as an implicit argument. Inside the method, you can call the block using the yield keyword with a value.
Apache has an effort under way to bring partial HOF support to the Java world, the Commons Functor project. The project looks pretty interesting, but might end up being pretty verbose to use. If its usability is similar to that of the CollectionUtils/Predicate functionality in the Apache Commons, I’m willing to give it a try. Either way, I hope Commons Functor comes of the Sandbox soon and starts playing with the big boys.