Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure function in let binding

If I have a function that evaluates to a function

(defn func1 [c1 c2]
  (fn [x1 x2]
    ...do some stuff with c1 c2 x1))

that I use elsewhere in a map or reduce, is it better to use inline

(defn func2 [x y z]
  (reduce (func1 x y) z (range 20)))

or to let bind it first

(defn func2 [x y z]
  (let [ffunc (func1 x y)]
    (reduce ffunc z (range 20))))

In the first case I would be worried that a new function over x and y is generated each step through the reduce.

like image 477
Jason Ozias Avatar asked May 24 '26 00:05

Jason Ozias


1 Answers

The evaluation of the function call (func1 x y) is done once in each case.

The rule for evaluating a function call in Clojure consists of evaluating all the expressions that are provided as its arguments and then invoking the function with those values.

If you define the following higher order function:

(defn plus []
  (println "calling plus")
  +)

And then call reduce in the following way:

(reduce (plus) [0 1 2 3])

A single calling plus is printed, showing the function plus is invoked only once.

The same thing happens when using the let form:

(let [f (plus)]
  (reduce f [0 1 2 3]))

Hope it helps.

like image 91
juan.facorro Avatar answered May 26 '26 12:05

juan.facorro



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!