[英]Clojure “map” function ordering guarantees?
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")
?
是的, (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中的元素將始終與原始集合具有相同的順序。 對於無序集合,您不能指望它們按特定順序排列,但事實並非如此。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.