I want to sort List objects in Scala, rather than sorting items in a list. For example, if I have two Ints lists:
val l1 = List(1, 2, 3, 7) val l2 = List(1, 2, 3, 4, 10)
I want to be able to put them in order, where l1> l2.
I created a case class that does what I need, but the problem is that when I use it, none of my other methods work. Do I need to implement all other methods in the class, for example, flatten, sortWith, etc.?
My class code looks like this:
class ItemSet(itemSet: List[Int]) extends Ordered[ItemSet] { val iSet: List[Int] = itemSet def compare(that: ItemSet) = { val thisSize = this.iSet.size val thatSize = that.iSet.size val hint = List(thisSize, thatSize).min var result = 0 var loop = 0 val ths = this.iSet.toArray val tht = that.iSet.toArray while (loop < hint && result == 0) { result = ths(loop).compare(tht(loop)) loop += 1 } if (loop == hint && result == 0 && thisSize != thatSize) { thisSize.compare(thatSize) } else result } }
Now, if I create an ItemSets Array, I can sort it:
val is1 = new ItemSet(List(1, 2, 5, 8)) val is2 = new ItemSet(List(1, 2, 5, 6)) val is3 = new ItemSet(List(1, 2, 3, 7, 10)) Array(is1, is2, is3).sorted.foreach(i => println(i.iSet)) scala> List(1, 2, 3, 7, 10) List(1, 2, 5, 6) List(1, 2, 5, 8)
Two methods that cause me problems:
def itemFrequencies(transDB: Array[ItemSet]): Map[Int, Int] = transDB.flatten.groupBy(x => x).mapValues(_.size)
I get an error:
An expression of type Map [Nothing, Int] does not match the expected type of Map [Int, Int]
And for this:
def sortListAscFreq(transDB: Array[ItemSet], itemFreq: Map[Int, Int]): Array[List[Int]] = { for (l <- transDB) yield l.sortWith(itemFreq(_) < itemFreq(_)) }
I got:
Cannot resolve sortWith character.
Is there a way that I can simply extend List [Int] so that I can sort the collection of lists without losing the functionality of other methods?