Clojure“地图”功能的订购保证?

时间:2019-08-03 12:07:59

标签: clojure

map的文档说:

user=> (doc map)

clojure.core/map
([f] [f coll] [f c1 c2] [f c1 c2 c3] [f c1 c2 c3 & colls])
  Returns a lazy sequence consisting of the result of applying f to
  the set of first items of each coll, followed by applying f to the
  set of second items in each coll, until any one of the colls is
  exhausted.  Any remaining items in other colls are ignored. Function
  f should accept number-of-colls arguments. Returns a transducer when
  no collection is provided.
nil

applying f to the set使我不确定f是否应用于传入的每个集合的第n个元素的序列,以给出结果的第n个元素顺序。

换句话说:

有保证吗

(map str [ "1" "2" "3" ] [ "a" "b" "c" ] )

将始终返回

("1a" "2b" "3c")

从不

("a1" "b2" "3c")

1 个答案:

答案 0 :(得分:3)

是的,(map str ["1" "2" "3"] ["a" "b" "c"])将始终返回("1a" "2b" "3c")

从源代码中可以看到它在(first s1) (first s2)上调用了该函数,然后调用了(map f (rest s1) (rest s2)),因此它总是按顺序处理它们:

https://github.com/clojure/clojure/blob/master/src/clj/clojure/core.clj#L2756

在启动之前,它会在每个集合上调用seq。对于像矢量这样的有序集合,结果seq中的元素将始终与原始集合具有相同的顺序。对于无序集合,您不能期望它们按特定顺序排列,但事实并非如此。