Bober02
Bober02

Reputation: 15341

Scala - select elements from ordered list

I am looking for a nice way to remove first N elements which are equal from the ordered list, e.g.

List(1,1,1,2,3,3)

should return

removeSame(list)  -> (1,1,1)

Is there a nice way to do it, rather than remove the head of the list and then use takeWhile on the remainder, and finally using dropwhile? I can think of simple non-functional solution but I was wondering whether any functional one also exists

Upvotes: 1

Views: 849

Answers (3)

Dahdahm
Dahdahm

Reputation: 513

Not the best way of doing it, but this also works:

def removeSame(l: List) = if( !l.isEmpty) l.groupBy( x => x)(l.head) else List()

Upvotes: 0

Luigi Plinge
Luigi Plinge

Reputation: 51109

The functional way to avoid the duplication of takeWhile and dropWhile to get a prefix and remainder is using span, i.e.

scala> val list = List(1,1,1,2,3,3)
list: List[Int] = List(1, 1, 1, 2, 3, 3)

scala> val (prefix, rest) = list span (_ == list.head)
prefix: List[Int] = List(1, 1, 1)
rest: List[Int] = List(2, 3, 3)

Upvotes: 7

pagoda_5b
pagoda_5b

Reputation: 7373

Is this what you look for?

scala> val l = List(1,1,1,2,3,3)
l: List[Int] = List(1, 1, 1, 2, 3, 3)

scala> l.takeWhile(_ == l.head)
res6: List[Int] = List(1, 1, 1)

scala> val l = List()
l: List[Nothing] = List()

scala> l.takeWhile(_ == l.head)
res7: List[Nothing] = List()

Upvotes: 3

Related Questions