Question

I'm defining a function within another function. Is one of the following approaches better, or more preferred, than the other?

(let [hey (println "hey there")] hey)

or

(let [hey (fn [] (println "hey here"))] (hey))
Was it helpful?

Solution

The first version isn't going to work the way you probably want it to. It's evaluated once during the let, and hey will get bound to the value nil. i.e. hey's value won't be a function.

The second is fine, and easy to read. Other approaches:

(let [hey0 #(println "hey0")] (hey0))

(letfn [(hey1 [] (println "hey1"))] (hey1))

No real rules for their use that I'm aware of. I use the #() reader macro form only for very short functions, and letfn if I'm defining a bunch of internal functions together.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top