Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure — partial in `->` macro

Tags:

clojure

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?

like image 335
Matthew H Avatar asked Mar 15 '13 22:03

Matthew H


People also ask

What is a macro in CL Clojure?

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.

What are thread-first macros in Clojure?

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:

What is a pure function in Clojure?

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.

Are all core constructs of Clojure primitives?

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:


1 Answers

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))

like image 92
Arthur Ulfeldt Avatar answered Sep 25 '22 11:09

Arthur Ulfeldt