3 ms·
A couple of things to point out for new Clojure readers. The 'def' form should not be used inside of 'defn'. Local bindings should use 'let'. When using the S
by nickik 7y ago
A couple of things to point out for new Clojure readers.
The 'def' form should not be used inside of 'defn'. Local bindings should use 'let'.
When using the STM, 'ref-set' should not be used most of the time.
(def names (ref []))
(defn add-name [name]
(dosync
(alter names conj name)))
The 'alter' function will call 'conj' and the return value will be the new value of 'names'.
- holtalanm 7y agoi was thinking that, too, while reading this. It has been a while since I wrote any Clojure, but I didn't remember ever using `ref-set` with STM. also, local bindings with `let` were the defacto standard.
- Scarbutt 7y agoWhen using STM, delete that code and start again without STM.
- bjoli 7y agoWhy should local bindings use let? In scheme internal (define ...) is defined in terms of letrec, which can add some overhead when letrec is unoptimized, but for schemes with optimized letrec (guile 3.0, chez, racket...) (define ...) is just as fast as let or let* unless you start doing cyclic references. The only real reason to not use Def would be if the bound symbol escapes the scope, but that would be ridiculous for a modern language.
- nickik 7y agoIn Clojure 'def' creates a 'var' and those are global in the namespace. > The only real reason to not use Def would be if the bound symbol escapes the scope, but that would be ridiculous for a modern language. Its not 'ridiculous' to have a consistent definition of what something does.
- pepper_sauce 7y agoIt does exactly what the documentation says it does: "Creates and interns or locates a global var with the name of symbol and a namespace of the value of the current namespace (ns)."