- About Scala
- Documentation
- Code Examples
- Software
- Scala Developers
Remove an item from a list based on its index
Fri, 2010-02-12, 15:49
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.
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.
Fri, 2010-02-12, 16:07
#2
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:
--
Daniel C. Sobral
I travel to the future all the time.
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.
Fri, 2010-02-12, 16:27
#3
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))
list - object = new list without object
2010/2/12 Germán Ferrari <german.ferrari@gmail.com>