joelittlejohn
joelittlejohn

Reputation: 11832

Practical examples of use for Clojure's some-> macro

Clojure 1.5 adds new threading macros, including:

The changelog has this contrived example to illustrate how some-> works:

user=> (defn die [x] (assert false))
#'user/die
user=> (-> 1 inc range next next next die)
AssertionError Assert failed: false  user/die (NO_SOURCE_FILE:65)
user=> (some-> 1 inc range next next next die)
nil

Chatting with other programmers, we found it difficult to think of a good, practical example for some->. When have you used some-> to solve a real-world problem?

Upvotes: 14

Views: 2445

Answers (3)

David J.
David J.

Reputation: 32715

The clojuredocs.org page on some-> has some some-> examples*:

(-> {:a 1} :b inc)
;; NullPointerException   clojure.lang.Numbers.ops (Numbers.java:942)

(some-> {:a 1} :b inc)
;; nil

* pun intended

Upvotes: 2

Alex Stoddard
Alex Stoddard

Reputation: 8344

some-> can be used to "auto-guard" a threaded series of processing steps where some part in the chain (especially in the middle) might return nil which would cause a logic failure further down the chain.

Particular examples could include threading clojure functions together with java interop where you would need to guard against null pointer exceptions.

Upvotes: 14

mac
mac

Reputation: 10085

A GitHub code search turns up quite a few examples

Upvotes: 6

Related Questions