Weird order in sets in Clojure

前端 未结 2 1558
死守一世寂寞
死守一世寂寞 2021-01-26 05:37

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

相关标签:
2条回答
  • 2021-01-26 05:42

    Sets are by default unordered. Therefore your results are fine, they contain the right elements. In general order is not important for sets.

    0 讨论(0)
  • 2021-01-26 05:49

    As ymonad said, Clojure sets are "randomly" ordered:

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

    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 the last example, we use into to add elements from the regular set into an empty sorted-set

    0 讨论(0)
提交回复
热议问题