2016-02-26 60 views
0

所以,我试图通过勇敢的Clojure工作。第三个练习是创建一个map函数,但不是返回一个列表,而应该返回一个集合。好的,所以我去了:Clojure奇怪的订单集

(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)}))))) 

但是然后发生了一些奇怪的事情。该功能的作品,种类。但是这些订单都搞乱了。我知道,在数学的顺序套是无关紧要的,但我不能想保持为什么会这样:

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} 

这里发生了什么?

+1

'#{}''创建散列set',如果你想要有序集合,可以使用'sorted-set' http://clojure.org/reference/data_structures#Sets – ymonad

回答

4

正如ymonad说,Clojure的集合是 “随机” 下令:

> (println #{ 1 2 3 4 5 }) 
#{1 4 3 2 5} 

字面一套语法#{1 2 3 4 5}只是短暂的(hash-set ...)。你可以得到一个有序集合,如下所示:

> (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} 

在上例中,我们使用into从正规集合中的元素添加到空sorted-set

2

设置默认为无序。因此你的结果很好,它们包含正确的元素。一般来说,顺序对组合来说并不重要。