Permalink
Browse files

CLJ-1343 - add some?, if-some, and when-some

Signed-off-by: Stuart Halloway <stu@cognitect.com>
  • Loading branch information...
1 parent 89dd5d5 commit 762db740f12690e668dbfb636ce5ef0a378190ee @puredanger puredanger committed with stuarthalloway Feb 14, 2014
Showing with 66 additions and 0 deletions.
  1. +44 −0 src/clj/clojure/core.clj
  2. +15 −0 test/clojure/test_clojure/control.clj
  3. +7 −0 test/clojure/test_clojure/logic.clj
View
44 src/clj/clojure/core.clj
@@ -501,6 +501,13 @@
:static true}
[x] (if x false true))
+(defn some?
+ "Returns true if x is not nil, false otherwise."
+ {:tag Boolean
+ :added "1.6"
+ :static true}
+ [x] (not (nil? x)))
+
(defn str
"With no args, returns the empty string. With one arg x, returns
x.toString(). (str nil) returns the empty string. With more than
@@ -1746,6 +1753,43 @@
(let [~form temp#]
~@body)))))
+(defmacro if-some
+ "bindings => binding-form test
+
+ If test is not nil, evaluates then with binding-form bound to the
+ value of test, if not, yields else"
+ {:added "1.6"}
+ ([bindings then]
+ `(if-some ~bindings ~then nil))
+ ([bindings then else & oldform]
+ (assert-args
+ (vector? bindings) "a vector for its binding"
+ (nil? oldform) "1 or 2 forms after binding vector"
+ (= 2 (count bindings)) "exactly 2 forms in binding vector")
+ (let [form (bindings 0) tst (bindings 1)]
+ `(let [temp# ~tst]
+ (if (nil? temp#)
+ ~else
+ (let [~form temp#]
+ ~then))))))
+
+(defmacro when-some
+ "bindings => binding-form test
+
+ When test is not nil, evaluates body with binding-form bound to the
+ value of test"
+ {:added "1.6"}
+ [bindings & body]
+ (assert-args
+ (vector? bindings) "a vector for its binding"
+ (= 2 (count bindings)) "exactly 2 forms in binding vector")
+ (let [form (bindings 0) tst (bindings 1)]
+ `(let [temp# ~tst]
+ (if (nil? temp#)
+ nil
+ (let [~form temp#]
+ ~@body)))))
+
(defn push-thread-bindings
"WARNING: This is a low-level function. Prefer high-level macros like
binding where ever possible.
View
15 test/clojure/test_clojure/control.clj
@@ -152,6 +152,21 @@
(exception))
))
+(deftest test-if-some
+ (are [x y] (= x y)
+ 1 (if-some [a 1] a)
+ false (if-some [a false] a)
+ nil (if-some [a nil] (exception))
+ 3 (if-some [[a b] [1 2]] (+ a b))
+ 1 (if-some [[a b] nil] b 1)
+ 1 (if-some [a nil] (exception) 1)))
+
+(deftest test-when-some
+ (are [x y] (= x y)
+ 1 (when-some [a 1] a)
+ 2 (when-some [[a b] [1 2]] b)
+ false (when-some [a false] a)
+ nil (when-some [a nil] (exception))))
(deftest test-cond
(are [x y] (= x y)
View
7 test/clojure/test_clojure/logic.clj
@@ -203,3 +203,10 @@
; Java objects
(new java.util.Date) ))
+(deftest test-some?
+ (are [expected x] (= expected (some? x))
+ false nil
+ true false
+ true 0
+ true "abc"
+ true []))

0 comments on commit 762db74

Please sign in to comment.