Reputation: 45
im new in Scala and im Looking for a way to do something like
val list = List(1, 0, 1, 2, 3, 1, 2, 0, 1, 2, 0, 3, 2, 0, 1)
mylist.sortWith(_ > _).partition(_ == 1).flatten
Problem is that partition() yields a tuple of lists but i need a list of lists.
The goal is to have this job done in one line without using other variable, optimisation in not a requirement.
A dirty/stupid way to achieve what im trying to do would be:
List(mylist.sortWith(_ > _).partition(_ == 1)._1, mylist.sortWith(_ > _).partition(_ == 1)._2).flatten
I am also wondering if i can cast the output of partition() to flatten it
Upvotes: 2
Views: 1013
Reputation: 1725
It seems like a missing feature of Scala, "a method to convert a tuple to a list", but you can use productIterator to get there...sort of. ProductIterator returns a List[Any] so it's rather ugly but you could do something like:
val list = List(1, 0, 1, 2, 3, 1, 2, 0, 1, 2, 0, 3, 2, 0, 1)
list
.sortBy(-_)
.partition( _ == 1 )
.productIterator.map( _.asInstanceOf[List[Int]] )
.toList.flatten
// Results in: List(1, 1, 1, 1, 1, 3, 3, 2, 2, 2, 2, 0, 0, 0, 0)
Just for a display of virtuosity you could also arrive at the same answer with
list.sortBy(-_).foldLeft(List[Int]()){case (a,1) => 1 +: a case (a,v) => a :+ v}
or:
list.sortBy(-_).sortWith((a,b) => a == 1)
Upvotes: 0
Reputation: 729
Here's one way to do it:
list.sorted.groupBy(_ == 1).values.toList
Upvotes: 5