passing functions as arguments in clojure
Asked Answered
D

1

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?

Dulcet answered 20/4, 2011 at 6:26 Comment(0)
M
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.

Mercurochrome answered 20/4, 2011 at 6:41 Comment(4)
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.'Dulcet
My confusion is that I have clearly passed an unquoted function 'cube' to 'something' and that works.Dulcet
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.Mercurochrome
Posted a new question here - #5728423Dulcet

© 2022 - 2024 — McMap. All rights reserved.