Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nested partials in Clojure

Tags:

clojure

How does the data structure get evaluated with the nested partials in the following:((partial (partial - 3)6)9). The inner partial yields -3, then we have ((partial -3)9). But how why does partial then makes (-3 - 9)? Where does it get the subtraction instruction from?

I would like some helps about the manner of reading and evaluating of this data representation by Clojure.


1 Answers

The claim that ((partial - 3) 6) is called during the course of evaluating this expression is incorrect, and this is at the core of the misunderstanding.

To make this simpler, let's break down:

((partial (partial - 3) 6) 9)

...instead, rewriting it as:

(let [p1 (partial - 3)]
  ((partial p1 6) 9)

Now, what does (partial p1 6) return? A function which calls p1, with its first argument being 6, and any subsequent arguments appended. Thus, we could again write it more verbosely as:

(let [p1 (partial - 3)
      p2 (partial p1 6)]
  (p2 9)

Thus, (p2 9) calls (p1 6 9), which calls (- 3 6 9). (- 3 6) is never invoked anywhere in the execution process, so the initial function call of - is never consumed until the final invocation with all arguments present.

(The actual implementation may optimize the middle call away, folding p1's arguments into p2, but there's no need to incorporate such optimizations into the conceptual model; behavior is equivalent to the above).

like image 167
Charles Duffy Avatar answered Feb 21 '26 15:02

Charles Duffy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!