Search code examples
clojurefirst-class-functions

passing functions as arguments in clojure


I have a function which takes a function and a number and returns the application of the function on the number, and a cube function:

(defn something [fn x]
  (fn x))

(defn cube [x]
  (* x x x))

When I call the function as follows it works:

(something cube 4)

but this returns an error:

(something Math/sin 3.14)

However, this works:

(something #(Math/sin %) 3.14)

What is the explanation?


Solution

  • Math.sin is not a function! It is a method straight from Java, and doesn't understand the various rules that Clojure functions have to follow. If you wrap it in a function, then that function can act as a proxy, passing arguments to the "dumb" method and returning the results to your "smart" function-oriented context.