Search code examples
clojure

Can the `map` function return a vector instead of a list?


Suppose i have the following function that replaces every 0 from a sequence with a set of numbers and every other number gets placed into a set with just that number.

(defn helper
  [lst]
  (map #(if (zero? %) 
          (sorted-set 1 2 3 4 5 6 7 8 9)
         #{%})
    lst) )

When i run it it returns (#{1 2 3 4 5 6 7 8 9} #{2} #{5} #{1 2 3 4 5 6 7 8 9} #{1 2 3 4 5 6 7 8 9}) but i want it to return the sets into a vector rather than a list like so: [#{1 2 3 4 5 6 7 8 9} #{2} #{5} #{1 2 3 4 5 6 7 8 9} #{1 2 3 4 5 6 7 8 9}]. What should i do so that it returns them in a vector than in a list ?


Solution

  • Use mapv. It is not lazy and always returns a vector.

    You should also bookmark The Clojure CheatSheet and always keep a browser tab open to it. Review a few functions daily until you are familiar with all of them. Just like learning the Java APIs, it takes a while but it is worth it.

    Be sure to see this list of Clojure documentation.

    Enjoy!