viebel
viebel

Reputation: 20670

In clojure, how to create a list applying 2 different functions on a collection of 2-elements vectors?

In Clojure, I have a collection coll of 2-elements vectors. I would like to create the collection obtained by applying f and g on the first and second elements on every vector of the collection, respectively. I think this is related to the list comprehension construct.

(def coll [[1 1000] [2 2000] [3 3000]])

IS there an idiomatic way for creating the following result?

 [[f(1) g(1000)] [f(2) g(2000)] [f(3) g(3000)]]

Upvotes: 1

Views: 458

Answers (3)

amalloy
amalloy

Reputation: 91857

To write this from scratch, I would do exactly what skuro did - it's simple, easy, and readable. But I also wrote a higher-order function to abstract this some time ago, named knit. So now I would write this as

(map (knit f g) [[1 1000] [2 2000] [3 3000]])

Upvotes: 1

skuro
skuro

Reputation: 13514

Again, list comprehension FTW:

(vec (for [[x y] [[1 1000] [2 2000] [3 3000]]] [(f x) (g y)]))

Upvotes: 5

osa1
osa1

Reputation: 7078

Yes,

(vec (map (fn [[p1 p2]] [(f p1) (g p2)])
          [[1 1000] [2 2000] [3 3000]]))

Upvotes: 4

Related Questions