On Wed, May 28, 2014 at 12:56:43AM -0700, sorin cristea wrote: > *( defn some-method [arg] (def thred (. Thread currentThred) > (println "on current thread" thread "use variable" arg))* > > 'thred' - is only visible inside of some-methd, because is a little > confuse for me your statement - "*`def` and `defn` create global bindings - > they are not variable assignments - and you don't want `def` nested into > `defn`.* "
In this case your "thred" var is actually visible globally, not only in
the function.
For example:
user=> (defn a-function [arg]
#_=> (def b (+ arg 1))
#_=> (/ b 2))
#'user/a-function
user=> (a-function 1)
1
user=> b
2
user=> (a-function 3)
2
user=> b
4
user=> (a-function 111)
56
user=> b
112
See how the value for "b" keeps changing? It's because "a-function" is
changing the *global* "b" value.
Let's try with another function, using "let" instead:
user=> (defn another-function [arg]
#_=> (let [barg (+ arg 1)]
#_=> (/ barg 2)))
#'user/another-function
user=> (another-function 1)
1
user=> barg
CompilerException java.lang.RuntimeException: Unable to resolve symbol: barg
in this context, compiling:(NO_SOURCE_PATH:0:0)
user=> (another-function 3)
2
user=> barg
CompilerException java.lang.RuntimeException: Unable to resolve symbol: barg
in this context, compiling:(NO_SOURCE_PATH:0:0)
user=> (another-function 111)
56
user=> barg
CompilerException java.lang.RuntimeException: Unable to resolve symbol: barg
in this context, compiling:(NO_SOURCE_PATH:0:0)
Here you can see that the local variable in the let, "barg" doesn't
escape to the global scope. In fact, there is no global "barg" variable
at all! It's completely contained within "another-function" now.
This is why we use "let" instead of "def". "def" creates a *global* var,
which is then in the global scope. "let" allows us to introduce our own
bindings for values within the current lexical scope. (There are some
other differences between them, but this is the strongest argument for
using "let" over "def", I think.)
Carlo
signature.asc
Description: Digital signature
