开发者

What does vector do in a map statement?

开发者 https://www.devze.com 2023-04-12 04:29 出处:网络
In a Clojure book, I found a map function with 3 args: (Map vec开发者_如何学JAVAtor (iterate inc 0) coll)

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

(Map vec开发者_如何学JAVAtor (iterate inc 0) coll)

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


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]).

0

精彩评论

暂无评论...
验证码 换一张
取 消