Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

clojure

Clojure 1.5 adds new threading macros, including:

  • some->
  • some->>

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?

like image 519
joelittlejohn Avatar asked May 03 '13 11:05

joelittlejohn


People also ask

When should I use Clojure macros?

Clojure has a programmatic macro system which allows the compiler to be extended by user code. Macros can be used to define syntactic constructs which would require primitives or built-in support in other languages. Many core constructs of Clojure are not, in fact, primitives, but are normal macros.

What does ->> mean in Clojure?

->> is the "thread-last" macro. It evaluates one form and passes it as the last argument into the next form. Your code is the equivalent of: (reduce str (interpose ", " (map :subject scenes)))


1 Answers

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.

like image 106
Alex Stoddard Avatar answered Sep 20 '22 09:09

Alex Stoddard