Search code examples
clojure

Clojure: How to reductions with a predicate?


In Clojure, how do I do reductions with a predicate?

For example:

(reductions - 1000 [500 600 300 90 180 180 30 80])

I want: (1) subtraction to be executed only if the subtrahend is not greater than the minuend; (2) if the condition in (1) is not met, leave the minuend as it is. Thus, the result should be:

=> (500 500 200 110 110 80 0)

Solution

  • Put your logic in a function and use that instead of -:

    user> (defn f [a b] (if (>= a b) (- a b) a))
    #'user/f
    
    user> (reductions f 1000 [500 600 300 90 180 180 30 80])
    (1000 500 500 200 110 110 110 80 0)
    

    reduction includes the initial value at the head of the result, you can use rest or next if you don't want it. Also I get 110 three times, which is different than your requested output, but I think it's correct according to your rules.

    Or if you prefer to use an anonymous function:

    (reductions #(if (> %1 %2) (- %1 %2) %1) 1000 [500 600 300 90 180 180 30 80])