开发者

passing functions as arguments in clojure

开发者 https://www.devze.com 2023-02-27 00:13 出处:网络
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:

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?


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号