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

后端 未结 6 634
广开言路
广开言路 2020-12-07 13:28

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

6条回答
  •  [愿得一人]
    2020-12-07 13:43

    There is no need to convert a vector to a list. Clojure will treat a vector as it would treat a list - as a sequence - when a sequence is required. For example,

    user=> (cons 0 [1 2 3])
    (0 1 2 3)
    

    If you need to make sure that the vector is being treated as a sequence, wrap it in seq:

    user=> (conj [1 2 3] 0) ; treated as a vector
    [1 2 3 0]
    
    user=> (conj (seq [1 2 3]) 0) ; treated as a sequence
    (0 1 2 3)
    

    If you have a vector of maps, and you want a set of maps, it doesn't matter that the vector holds maps. You just convert the vector to a set as usual:

    user=> (set [{:a 1, :b 2} {"three" 3, "four" 4}])
    #{{:a 1, :b 2} {"four" 4, "three" 3}}
    

提交回复
热议问题