2

This seems wrong to me - why is the order of the elements changed from the order they are built?

scala> var list = collection.immutable.TreeSet(1, 3, 2, 5, 0)
list: scala.collection.immutable.TreeSet[Int] = TreeSet(0, 1, 2, 3, 5)

scala> var xml = <list>{ list.map(number => { <number>{number}</number> }) }</list>
xml: scala.xml.Elem = <list><number>3</number><number>1</number><number>2</number><number>5</number><number>0</number></list>

scala> var xml = <list>{ list.map(number => { println(number); <number>{number}</number> }) }</list>
0
1
2
3
5
xml: scala.xml.Elem = <list><number>3</number><number>1</number><number>2</number><number>5</number><number>0</number></list>
Dave Clay
  • 21
  • 1

1 Answers1

2

When you map over the TreeSet, it creates a new set. The new Set does not use the natural ordering for integers, of course, since its elements are not integers. In fact, since there is no natural Ordering for Elem, the new set is unordered. You can achieve the ordering you're looking for with:

var xml = <list>{ list.toSeq map (n => <number>{n}</number>) }</list>
Aaron Novstrup
  • 20,967
  • 7
  • 70
  • 108
  • Actually, I doubt it created a new `TreeSet`, as there's no `Ordering` for the result. More likely, it descended to a `Set`, which defaults to `HashSet`. – Daniel C. Sobral Jan 29 '12 at 00:45