Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Clojure is there an easy way to convert between list types?

Tags:

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?

like image 711
yazz.com Avatar asked Feb 23 '11 09:02

yazz.com


1 Answers

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" 

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.

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.

like image 65
Arthur Ulfeldt Avatar answered Sep 24 '22 00:09

Arthur Ulfeldt