I've just started using Clojure, and I was wondering why the following doesn't work as expected:
(-> 5
-
(partial + 5))
I would expect the result of this expression to be 0 (-5 + 5), but instead the whole thing seems to be a partial.
(macroexpand `(-> 5 - (partial + 5))
#_=> )
(clojure.core/partial (clojure.core/-> 5 clojure.core/-) clojure.core/+ 5)
Why is this, and how can I do what I wanted to?
Clojure is no exception and provides simple macro facilities for developers. Macros are used to write code-generation routines, which provide the developer a powerful way to tailor the language to the needs of the developer.
Threading macros, also known as arrow macros, convert nested function calls into a linear flow of function calls, improving readability. The thread-first macro (->) In idiomatic Clojure, pure functions transform immutable data structures into a desired output format. Consider a function that applies two transformations to a map:
In idiomatic Clojure, pure functions transform immutable data structures into a desired output format. Consider a function that applies two transformations to a map: transform is an example of a common pattern: it takes a value and applies multiple transformations with each step in the pipeline taking the result of the previous step as its input.
Many core constructs of Clojure are not, in fact, primitives, but are normal macros. Some macros produce simple combinations of primitive forms. For example, when combines if and do:
needs an extra set of parens:
user> (-> 5 - ((partial + 5)))
0
the ->
macro inserts the result of the previous expression as the second argument in the list so in your example it would exand to (partial (- 5) + 5)
with the extra () it gets inserted after the partial function ((partial + 5) (- 5))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With