Very basic question… Could you please tell me what is the most idiomatic way to bind var to a specified value when it is bound to nil or any other incorrect value?
In case of nil the simplest way I came with is (let [y (if y y 123)] ...), like this:
(defn just-for-test [x y]
(let [y (if y y (get-some-data))]
; do something with x and y
(println x y)
))
Of course, the wrong value doesn’t have to be nil. It could be for example empty collection which would look like (let [y (if (seq y) y [:a :b :c])] ...).
The reason I’m asking is that the code y (if y y 123] looks funny so I’m not sure if it’s just me being unexperienced and the code is OK
For the other example (or (seq y) [:a :b :c]) can work as long as the remaining code using the value of the expression expects a sequence and not a vector; otherwise what you have would be fine.
or is nice for returning something else in the presence of nil and false, but I wanted to say that you shouldn’t be afraid to create small utility functions for yourself when you need one, I think in Clojure you should embrace utility functions.
When I started with Clojure I wrote a lot of utility functions and then I realized that 99% already exist in clojure.core ;-). Good learning but not very useful code at the end. This is the reason I’m slightly opposed to write small utility functions since I think most of functions that people really wanted are already there. I just need to discover them ;-).