Dave Clay
Dave Clay

Reputation: 21

How do I create ordered xml elements in scala?

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>

Upvotes: 2

Views: 180

Answers (1)

Aaron Novstrup
Aaron Novstrup

Reputation: 21017

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>

Upvotes: 2

Related Questions