Clojure中的顺序奇怪 [英] Weird order in sets in Clojure
问题描述
因此,我正在尝试通过勇敢的Clojure来努力。第三个练习包括创建一个map函数,但是与其返回列表,不如返回一个列表。好的,我去了:
So, I'm trying to work my way through Brave Clojure. The third exercise consists on creating a map function but instead of returning a list it should return a set. OK, so there I go:
(defn mapset
[f lst]
(loop [[head & remaining] lst
final-set #{}]
(if (empty? remaining)
(into final-set #{(f head)})
(recur remaining
(into final-set #{(f head)})))))
但是随后发生了一些奇怪的事情。该功能有效,有点。但是订单全都弄乱了。我知道在数学中集合的顺序是无关紧要的,但是我无法不知道为什么会这样:
But then something weird happens. The function works, kind of. But the order is all messed up in the sets. I know that in mathematics order in sets is irrelevant, but I can't keep from wondering why is this happening:
clojure-noob.core=> (mapset identity [1])
#{1}
clojure-noob.core=> (mapset identity [1 2])
#{1 2}
clojure-noob.core=> (mapset identity [1 2 3])
#{1 3 2}
clojure-noob.core=> (mapset identity [1 2 3 4])
#{1 4 3 2}
clojure-noob.core=> (mapset identity [1 2 3 4 5])
#{1 4 3 2 5}
clojure-noob.core=> (mapset identity [1 2 3 4 5 6])
#{1 4 6 3 2 5}
也不只是身份功能。
clojure-noob.core=> (mapset inc [1 2 3])
#{4 3 2}
发生了什么这里?
推荐答案
正如ymonad所说,Clojure集是随机排序的:
As ymonad said, Clojure sets are "randomly" ordered:
> (println #{ 1 2 3 4 5 } )
#{1 4 3 2 5}
文字集语法#{1 2 3 4 5}
只是(哈希集...)$ c $的缩写c>。您可以得到如下所示的排序集:
The literal set syntax #{1 2 3 4 5}
is just short for (hash-set ...)
. You can get a sorted set as shown:
> (hash-set 1 2 3 4 5 6)
#{1 4 6 3 2 5}
> (sorted-set 1 2 3 4 5 6)
#{1 2 3 4 5 6}
> (into (sorted-set) #{1 2 3 4 5 6} )
#{1 2 3 4 5 6}
在上一个示例中,我们使用 in 将常规集中的元素添加到空的
sorted-set
In the last example, we use into
to add elements from the regular set into an empty sorted-set
这篇关于Clojure中的顺序奇怪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!