Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 826
Pranav Avatar asked Apr 20 '11 06:04

Pranav


People also ask

What is a function with multiple arguments in Clojure?

Clojure - Functions with Multiple Arguments. Clojure functions can be defined with zero or more parameters. The values you pass to functions are called arguments, and the arguments can be of any type. The number of parameters is the function’s arity. This chapter discusses some function definitions with different arities.

Is CL Clojure a functional language?

Clojure is a functional language. Functions are first-class and can be passed-to or returned-from other functions. Most Clojure code consists primarily of pure functions (no side effects), so invoking with the same inputs yields the same output.

What is a partial function in Clojure?

In Clojure, the partial function is a more general version of this. 13) Define a function two-fns which takes two functions as arguments, f and g. It returns another function which takes one argument, calls g on it, then calls f on the result, and returns that.

How do you return a function from a function in Clojure?

They can be assigned as values, passed into functions, and returned from functions. It’s common to see function definitions in Clojure using defn like (defn foo … ) . However, this is just syntactic sugar for (def foo (fn …​)) fn returns a function object. defn returns a var which points to a function object.


1 Answers

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.

like image 179
amalloy Avatar answered Nov 09 '22 14:11

amalloy