In Scheme I can do something like this:
(define (adder)
(define (one) 1)
(define (two) 2)
(+ (one) (two)))
Calling adder
results in 3
while calling one
will yield an error since one
is only visible within the scope of adder
.
In Clojure if I do something similar
(defn adder []
(defn one [] 1)
(defn two [] 2)
(+ (one) (two)))
one
and two
will pollute my namespace since defn
uses def
internally which creates bindings in the current namespace.
Is there a function/macro which creates named functions in local scope?
The reason for my question is that I got used to the way Scheme works. Naming my local functions that way often makes my code more readable.
Try letfn:
Takes a vector of function specs and a body, and generates a set of bindings of functions to their names. All of the names are available in all of the definitions of the functions, as well as the body.
(defn adder []
(letfn [(one [] 1)
(two [] 2)]
(+ (one) (two))))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With