Question

If I use the reductions function like so:

(reductions + [1 2 3 4 5])

Then I get

(1 3 6 10 15)

Which is great - but I'd like to apply a binary function in the same way without the state being carried forward - something like

(magic-hof + [1 2 3 4 5])

leads to

(1 3 5 7 9)

ie it returns the operation applied to the first pair, then steps 1 to the next pair.

Can someone tell me the higher-order function I'm looking for? (Something like reductions)

This is my (non-working) go at it:

(defn thisfunc [a b] [(+ a b) b])

(reduce thisfunc [1 2 3 4 5])
Was it helpful?

Solution

You can do it with map:

(map f coll (rest coll))

And if you want a function:

(defn map-pairwise [f coll]
  (map f coll (rest coll)))

And if you really need the first element to remain untouched (thanx to juan.facorro's comment):

(defn magic-hof [f [x & xs :as s]]
  (cons x (map f s xs)))

OTHER TIPS

partition will group your seq:

user> (->> [1 2 3 4 5] (partition 2 1) (map #(apply + %)) (cons 1))
(1 3 5 7 9)

So, you want to apply a function to subsequent pairs of elements?

(defn pairwise-apply
  [f sq]
  (when (seq sq)
    (->> (map f sq (next sq))
         (cons (first sq)))))

Let's try it:

(pairwise-apply + (range 1 6))
;; => (1 3 5 7 9)

This is sufficient:

(#(map + (cons 0 %) %) [1 2 3 4 5])
;; => (1 3 5 7 9)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top