在 Clojure 中是否有一种简单的方法可以在列表类型之间进行转换? [英] In Clojure is there an easy way to convert between list types?

查看:25
本文介绍了在 Clojure 中是否有一种简单的方法可以在列表类型之间进行转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我想要一个向量时,我经常发现自己使用了一个惰性列表,反之亦然.此外,有时我有一个地图矢量,当我真的想要一组地图时.是否有任何帮助函数可以帮助我在这些类型之间进行转换?

I am often finding myself using a lazy list when I want a vector, and vice versa. Also, sometimes I have a vector of maps, when I really wanted a set of maps. Are there any helper functions to help me to convert between these types?

推荐答案

别忘了可靠的旧 into 可以让你把任何 seqable (list, vector, map, set, sorted-map) 和一个你想要填充的空容器,然后把它放入.

Let's not forget that trusty old into lets you take anything seqable (list, vector, map, set, sorted-map) and an empty container you want filled, and puts it into it.

(into [] '(1 2 3 4)) ==> [1 2 3 4]         "have a lazy list and want a vector"
(into #{} [1 2 3 4]) ==> #{1 2 3 4}        "have a vector and want a set"
(into {} #{[1 2] [3 4]}) ==> {3 4, 1 2}    "have a set of vectors want a map"
(into #{} [{1 2} {3 4}]) ==> #{{1 2} {3 4}} "have a vector of maps want a set of maps"

intoconj 的包装器,它是根据集合的类型将新条目适当地插入到集合中的基本抽象.使这个流程如此顺利的原则是 Clojure 建立在 可组合抽象 之上,在本例中,into 位于 conj 之上,位于集合之上和 seq.

into is a wrapper around conj, which is the base abstraction for inserting new entries appropriately into a collection based on the type of the collection. The principle that makes this flow so nicely is that Clojure is build on composable abstractions, in this case into on top of conj on top of collection and seq.

如果接收者是在运行时传入的,上面的例子仍然可以很好地组合:因为底层抽象(seqconj)是为所有集合实现的(还有很多 Java 的集合),所以更高的抽象不需要担心很多与数据相关的特殊情况.

The above examples would still compose well if the recipient was being passed in at run time: because the underlying abstractions (seq and conj) are implemented for all the collections (and many of Java's collections also), so the higher abstractions don't need to worry about lots of special data-related corner cases.

这篇关于在 Clojure 中是否有一种简单的方法可以在列表类型之间进行转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆