Skip to content

Commit 2444242

Browse files
timothypratleystuarthalloway
authored andcommitted
added fnil to supply default values #257
Signed-off-by: Stuart Halloway <[email protected]>
1 parent eb4502c commit 2444242

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

src/clj/clojure/core.clj

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5669,6 +5669,29 @@
56695669
(cons x (keepi (inc idx) (rest s)))))))))]
56705670
(keepi 0 coll))))
56715671

5672+
(defn fnil
5673+
"Takes a function f, and returns a function that calls f, replacing
5674+
a nil first argument to f with the supplied value x. Higher arity
5675+
versions can replace arguments in the second and third
5676+
positions (y, z). Note that the function f can take any number of
5677+
arguments, not just the one(s) being nil-patched."
5678+
([f x]
5679+
(fn
5680+
([a] (f (if (nil? a) x a)))
5681+
([a b] (f (if (nil? a) x a) b))
5682+
([a b c] (f (if (nil? a) x a) b c))
5683+
([a b c & ds] (apply f (if (nil? a) x a) b c ds))))
5684+
([f x y]
5685+
(fn
5686+
([a b] (f (if (nil? a) x a) (if (nil? b) y b)))
5687+
([a b c] (f (if (nil? a) x a) (if (nil? b) y b) c))
5688+
([a b c & ds] (apply f (if (nil? a) x a) (if (nil? b) y b) c ds))))
5689+
([f x y z]
5690+
(fn
5691+
([a b] (f (if (nil? a) x a) (if (nil? b) y b)))
5692+
([a b c] (f (if (nil? a) x a) (if (nil? b) y b) (if (nil? c) z c)))
5693+
([a b c & ds] (apply f (if (nil? a) x a) (if (nil? b) y b) (if (nil? c) z c) ds)))))
5694+
56725695
(defn- ^{:dynamic true} assert-valid-fdecl
56735696
"A good fdecl looks like (([a] ...) ([a b] ...)) near the end of defn."
56745697
[fdecl]

test/clojure/test_clojure/other_functions.clj

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,17 @@
5050
"bar" 'bar
5151
"quux" "quux"))
5252

53+
(deftest test-fnil
54+
(are [x y] (= x y)
55+
((fnil + 0) nil 42) 42
56+
((fnil conj []) nil 42) [42]
57+
(reduce #(update-in %1 [%2] (fnil inc 0)) {}
58+
["fun" "counting" "words" "fun"])
59+
{"words" 1, "counting" 1, "fun" 2}
60+
(reduce #(update-in %1 [(first %2)] (fnil conj []) (second %2)) {}
61+
[[:a 1] [:a 2] [:b 3]])
62+
{:b [3], :a [1 2]}))
63+
5364
; time assert comment doc
5465

5566
; partial

0 commit comments

Comments
 (0)