6

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?

Svante
  • 50,694
  • 11
  • 78
  • 122
Pranav
  • 3,340
  • 8
  • 35
  • 48

1 Answers1

14

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.

amalloy
  • 89,153
  • 8
  • 140
  • 205
  • Thanks, now I understand. Actually I was trying to understand macros when this confusion arose. Can you explain this line to me? - 'Since macros don't evaluate their arguments, unquoted function names can be passed to them and calls to the functions with arguments can be constructed. Function definitions cannot do this and instead must be passed anonymous functions that wrap calls to functions.' – Pranav Apr 20 '11 at 06:56
  • My confusion is that I have clearly passed an unquoted function 'cube' to 'something' and that works. – Pranav Apr 20 '11 at 06:59
  • 1
    Can you ask this as a real SO question rather than in the comments? The formatting in here is pretty lackluster, and I don't really want to add "another answer" to a completely unrelated question. – amalloy Apr 20 '11 at 07:38
  • Posted a new question here - http://stackoverflow.com/questions/5727923/macros-and-functions-in-clojure – Pranav Apr 20 '11 at 09:07