eat_a_lemon
eat_a_lemon

Reputation: 3208

trying to understand a clojure "let" example

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

I am trying to figure out this let example in clojure. What is the y variable it never seems to be set to anything. I do not understand the let syntax.

Upvotes: 14

Views: 9007

Answers (3)

aarti
aarti

Reputation: 2865

Let expression is standard in many functional programming languages. What is the "let" keyword in functional languages like F# and OCaml for?

Upvotes: 1

Barmar
Barmar

Reputation: 780787

(let [y x]
    <body>)

evaluates <body> in a lexical context where y is bound to the value of x.

See the Clojure documentation for the description of let syntax. The general form is:

(let [sym1 val1
      sym2 val2
      sym3 val3
      ... ]
    <body>)

Each symN is bound to the corresponding valN.

Upvotes: 19

djhaskin987
djhaskin987

Reputation: 10057

This function:

(defn make-adder [x]
  (let [y x]
    (fn [z] (+ y z))))

Itself returns a first-class function (a function that can be returned, passed around and assigned to a name just like any other value). Inside the let, x is bound to y, and so the function above is equivalent to this function below:

(defn make-adder [x]
  (fn [z] (+ x z)))

So that when make-adder is called with the value 2, it returns this first-class function:

(fn [z] (+ 2 z))

Remember, a first-class function can be assigned to a name, as in this line:

(def add2 (made-adder 2))

The line above is therefore equivalent to this code:

(def add2 (fn [z] (+ 2 z)))

And so is equivalent to this code also:

(defn add2 [z] (+ 2 z))

Which means that when add2 is called:

(add2 4)

The expression above evaluates to this:

(+ 2 4)

Which evaluates to 6.

Upvotes: 11

Related Questions