Pure Danger Tech


navigation
home

2 is a smell

12 Oct 2011

Clojure is a sequence processing languagesequences are the core abstraction between data and function. I have come to the notion that code that handles 1 or N of something is far more likely to be correct than code that handles 2 (or any fixed number > 1).

In general, any time you use the second function, your warning sensors should go off. Take a function that adds x-y vectors:

(defn add-vectors [va vb]
 [(+ (first va) (first vb)) (+ (second va) (second vb))])

(add-vectors [1 2] [3 4])
;; [4 6]

Those first and second functions should be SCREAMING at you that there is implicit structure here. Destructuring is sometimes a worthy next step that allows you to make that implicit structure explicit:

(defn add-vectors [[vax vay] [vbx vby]]
 [(+ vax vbx) (+ vay vby)])

However, we are still explicitly handling only two-dimensional vectors. The code would be better handling N-dimensional vectors instead:

(defn add-vectors [va vb]
   (vec (map + va vb)))

And I sincerely hope that you are now asking yourself, “why are we adding only two vectors and not N?”

Indeed:

(defn add-vectors [& vs]
 (vec (apply map + vs)))