Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Idiomatic no-op/"pass"

Tags:

clojure

What's the (most) idiomatic Clojure representation of no-op? I.e.,

(def r (ref {}))
...
(let [der @r]
    (match [(:a der) (:b der)]
        [nil nil] (do (fill-in-a) (fill-in-b))
        [_ nil] (fill-in-b)
        [nil _] (fill-in-a)
        [_ _] ????))

Python has pass. What should I be using in Clojure?

ETA: I ask mostly because I've run into places (cond, e.g.) where not supplying anything causes an error. I realize that "most" of the time, an equivalent of pass isn't needed, but when it is, I'd like to know what's the most Clojuric.

like image 701
swizzard Avatar asked Jul 28 '14 23:07

swizzard


3 Answers

There are no "statements" in Clojure, but there are an infinite number of ways to "do nothing". An empty do block (do), literally indicates that one is "doing nothing" and evaluates to nil. Also, I agree with the comment that the question itself indicates that you are not using Clojure in an idiomatic way, regardless of this specific stylistic question.

like image 126
noisesmith Avatar answered Jan 01 '23 11:01

noisesmith


The most analogous thing that I can think of in Clojure to a "statement that does nothing" from imperative programming would be a function that does nothing. There are a couple of built-ins that can help you here: identity is a single-arg function that simply returns its argument, and constantly is a higher-order function that accepts a value, and returns a function that will accept any number of arguments and return that value. Both are useful as placeholders in situations where you need to pass a function but don't want that function to actually do much of anything. A simple example:

(defn twizzle [x]
  (let [f (cond (even? x) (partial * 4)
                (= 0 (rem x 3)) (partial + 2)
                :else identity)]
    (f (inc x))))

Rewriting this function to "do nothing" in the default case, while possible, would require an awkward rewrite without the use of identity.

like image 36
Alex Avatar answered Jan 01 '23 11:01

Alex


I see the keyword :default used in cases like this fairly commonly.
It has the nice property of being recognizable in the output and or logs. This way when you see a log line like: "process completed :default" it's obvious that nothing actually ran. This takes advantage of the fact that keywords are truthy in Clojure so the default will be counted as a success.

like image 35
Arthur Ulfeldt Avatar answered Jan 01 '23 11:01

Arthur Ulfeldt