jayunit100
jayunit100

Reputation: 17648

What does vector do in a map statement?

In a Clojure book, I found a map function with 3 args:

(Map vector (iterate inc 0) coll)

What is the vector doing? How is it that this function accepts 3 args instead of the standard 2?

Upvotes: 2

Views: 91

Answers (1)

Chuck
Chuck

Reputation: 237010

The map function accepts a variable number of arguments. The required first argument is a function, and then you can pass any number of collections after. When more than one collection is passed, the corresponding element from each collection will be passed as an argument to the function (e.g. if you pass one collection, the function will receive one argument, and if you pass three collections, it will receive three arguments).

As for vector, it does the same thing the vector function usually does — make a vector out of its arguments. For example, (vector 1 100 1000) gives [1 100 1000]. In this case, its arguments will be the nth elements of two collections:

  1. An infinite sequence of integers starting at zero

  2. Whatever is in coll

In effect, this transforms each item in coll into a vector containing the item's index followed by the item. So if coll is [a b c], for example, it will give you ([0 a] [1 b] [2 c]).

Upvotes: 8

Related Questions