Oliver Mooney
Oliver Mooney

Reputation: 155

composition and partial composition of functions in Clojure

I have a nested vector of vectors, like [[1 2 3] [4 5 6] [7 8 9]] and I want to increment the values of each sub-vector, then find the max of each sub-vector. The formulation I'm using is:

(map (comp (partial apply max) (partial map inc)) [[1 2 3] [4 5 6] [7 8 9]])

Is there a better way?

Upvotes: 2

Views: 146

Answers (2)

Thumbnail
Thumbnail

Reputation: 13483

Based on @xsc's answer, but respecting the order of operations ...

(map #(->> % (map inc) (apply max)) [[1 2 3] [4 5 6] [7 8 9]])
;(4 7 10)

Upvotes: 1

xsc
xsc

Reputation: 6073

To achieve your goal you can combine max/inc and save one call to map:

(map (comp inc #(apply max %)) [[1 2 3] [4 5 6] [7 8 9]])
;; => (4 7 10)

But that's only a marginal improvement and actually inverts the order of operations. Might be more readable, though.

Upvotes: 1

Related Questions