简体   繁体   English

在Clojure中,如何创建在2个元素向量的集合上应用2个不同功能的列表?

[英]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. 在Clojure中,我有2个元素向量的集合coll 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. 我想创建通过分别在集合的每个向量的第一个和第二个元素上应用fg获得的集合。 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)]]

同样,列表理解FTW:

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

Yes, 是,

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

To write this from scratch, I would do exactly what skuro did - it's simple, easy, and readable. 为了从头开始编写此代码,我将完全执行skuro所做的工作-它简单,容易且可读。 But I also wrote a higher-order function to abstract this some time ago, named knit . 但是我也写了一个高阶函数来抽象这个,叫做knit So now I would write this as 所以现在我将其写为

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM