David
David

Reputation: 77

Using a var outside let - clojure

Is there any way in clojure to allow a var defined within a let structure to be used elsewhere in the namespace?

The problem that I am having is that I need two seperate values from the let.

For example if I have the code

    (defn example [x y z]
       (let [
          xy (* x y)
          xz (* x z)]
        xz))

Is there any way for me to use xy outside the let?

I should also note that xy and xz are just examples in this case, the real data sets are hash-maps and that I have tried using seperate functions to obtain each of sets seperately but because of the nature of the system that I am using this doesn't seem possible.

Upvotes: 2

Views: 284

Answers (2)

noisesmith
noisesmith

Reputation: 20194

when you need multiple results from a single function, destructuring is useful

(defn example
  [x y z]
  (let [xy (* x y)
        xz (* x z)]
    [xy xz]))

(defn other-example
  (let [[xy xz] (example 1 2 3)]
    (println 'xy xy 'xz xz)))

Upvotes: 2

Óscar López
Óscar López

Reputation: 235984

No, by definition the variables defined in a let will only be visible inside it. If you need a variable outside maybe you should use a global definition ... but in general that's not a good idea. How about passing around the values as parameters to the other functions that need it?

Upvotes: 1

Related Questions