7

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?

1 Answer 1

15

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.

Sign up to request clarification or add additional context in comments.

4 Comments

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.'
My confusion is that I have clearly passed an unquoted function 'cube' to 'something' and that works.
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.
Posted a new question here - stackoverflow.com/questions/5727923/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.