Unable to understand this clojure make-adder example

I'm trying to read a little on Clojure, but I hit a brick wall with the following basic example:

(defn make-adder [x]
  (let [y x]
    (fn [z] (+ y z))))
(def add2 (make-adder 2))
(add2 4)
-> 6

What I do not understand is how add2to pass the number 4 to the make-adder function, and how this function is rotated to assign that number z.

Thanks in advance!

+5
source share
2 answers

make-adderreturns a function that takes one parameter (z), the parameter passed to make-adderis used to assign the value of y. add2is set equal to the result of the evaluation make-adderwith parameter 2. Thus, it is add2set equal to the function returned from make-adder, which (since y was assigned to the parameter from make-adder) looks like

(fn [z] (+ 2 z))

, (add2 4) , 6. ?

+6

, , .

make-adder ( )

(defn make-adder [x]
  "Returns a function that returns the sum of x and yet to be supplied z."
  (fn [z] (+ z x))))

, x z, make- . , Clojure, .

, , , ( partial add2),

(defn make-adder
  "Returns sum of x and y." 
  [x y] 
  (+ x y))

add2 2 x:

(def add2 (partial make-adder 2))

(add2 2), 4, (add2 3), 5 ..

+3

All Articles