This page is no longer maintained — Please continue to the home page at www.scala-lang.org

Remove an item from a list based on its index

3 replies
gerferra
Joined: 2009-08-26,
User offline. Last seen 1 year 38 weeks ago.
Hello.

I'm just not finding a direct way to remove an item from a list based on its index. I'm looking for something like this:

list.remove (index)

How do you do this in Scala?

Thank you.

Regards,
Germain.
Stefan Langer
Joined: 2009-10-23,
User offline. Last seen 42 years 45 weeks ago.
Re: Remove an item from a list based on its index
Immutable list
list - object = new list without object

2010/2/12 Germán Ferrari <german.ferrari@gmail.com>
Hello.

I'm just not finding a direct way to remove an item from a list based on its index. I'm looking for something like this:

list.remove (index)

How do you do this in Scala?

Thank you.

Regards,
Germain.

dcsobral
Joined: 2009-04-23,
User offline. Last seen 38 weeks 5 days ago.
Re: Remove an item from a list based on its index
Given that this operation is highly inefficient with lists (immutable ones, anyway), it does not exist.   def remove[T](list: List[T]) = {   val (start, _ :: end) = list.splitAt(index)   start ::: end }

On Fri, Feb 12, 2010 at 12:48 PM, Germán Ferrari <german.ferrari@gmail.com> wrote:
Hello.

I'm just not finding a direct way to remove an item from a list based on its index. I'm looking for something like this:

list.remove (index)

How do you do this in Scala?

Thank you.

Regards,
Germain.



--
Daniel C. Sobral

I travel to the future all the time.
extempore
Joined: 2008-12-17,
User offline. Last seen 35 weeks 3 days ago.
Re: Remove an item from a list based on its index

On Fri, Feb 12, 2010 at 12:48:54PM -0200, Germán Ferrari wrote:
> I'm just not finding a direct way to remove an item from a list based
> on its index. I'm looking for something like this:
>
> list.remove (index)
>
> How do you do this in Scala?

If you're me you find yourself adding a method you keep needing. These
are in the pattern matcher somewhere.

/** Drops the 'i'th element of a list.
*/
def dropIndex[T](xs: List[T], n: Int) = {
val (l1, l2) = xs splitAt n
l1 ::: (l2 drop 1)
}

/** Extract the nth element of a list and return it and the remainder.
*/
def extractIndex[T](xs: List[T], n: Int): (T, List[T]) =
(xs(n), dropIndex(xs, n))

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland