Idiomatic way to change (rebind) var when it's nil / wrong

Hi All,

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 :wink: so I’m not sure if it’s just me being unexperienced and the code is OK

Thank you.

Kind regards,

Mark

I often use (or y 123).

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.

Cool! I love this ;-). I didn’t realize or doesn’t return boolean. Thank you.

(or (not-empty y) [:a :b :c]) will preserve the collection type so you can handle vectors, sets, maps, etc.

2 Likes

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.

(defn when-default
  [pred expr default]
  (if (pred expr) default expr))

(when-default seq [] [:a :b :c])
;> []

(when-default seq [1] [:a :b :c])
;> [:a :b :c]

(when-default nil? 1 [:a :b :c])
;> 1

(when-default nil? nil [:a :b :c])
;> [:a :b :c]

Cool, thank you.

Very nice, thank you.

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 ;-).

1 Like