O'Reilly logo

Clojure Programming by Brian Carper, Christophe Grand, Chas Emerick

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

First-Class and Higher-Order Functions

Despite the great variability about what “functional programming” means in different languages, one requirement is consistent: functions must themselves be values, so that they may be treated like any other data, accepted as arguments and returned as results by other functions.

Functions as data permits a means of abstraction that a language without first-class functions lacks. As a simple example, imagine writing a function that simply calls some other function twice. Rather than call a specific function, our call_twice function should be generic enough to call any function on any argument.

This is trivial in a language with first-class functions. In Ruby[48] and Python:

# Ruby
def call_twice(x, &f)
  f.call(x)
  f.call(x)
end

call_twice(123) {|x| puts x}

# Python
def call_twice(f, x):
  f(x)
  f(x)

call_twice(print, 123)

The Clojure code is just as simple:

(defn call-twice [f x]
  (f x)
  (f x))

(call-twice println 123)
; 123
; 123

By contrast, it would be difficult to write even this trivial function in Java. Ironically, the majority language on the JVM does not provide for functions as first class values. In Java, code may only exist within methods, which must be associated with a class, and methods can’t be referenced as objects short of resorting to Java’s reflection API.

Classes defined only to contain static utility methods—like java.lang.Math—end up functioning as impoverished namespaces created to compensate for the lack of first-class functions. Other ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required