Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing nth element from a String Array in Scala

Tags:

scala

Assuming I have a (what I assume is mutable by default) Array[String]

How in Scala can I simply remove the nth element?

No simple method seems to be available.

Want Something like (I made this up):

def dropEle(n: Int): Array[T]
Selects all elements except the nth one.

n
the subscript of the element to drop from this Array.
Returns an Array consisting of all elements of this Array except the 
nth element, or else the complete Array, if this Array has less than 
n elements.

Many thanks.

like image 521
nfc-uk Avatar asked Jan 11 '14 00:01

nfc-uk


2 Answers

That is what views are for.

scala> implicit class Foo[T](as: Array[T]) {
     | def dropping(i: Int) = as.view.take(i) ++ as.view.drop(i+1)
     | }
defined class Foo

scala> (1 to 10 toArray) dropping 3
warning: there were 1 feature warning(s); re-run with -feature for details
res9: scala.collection.SeqView[Int,Array[Int]] = SeqViewSA(...)

scala> .toList
res10: List[Int] = List(1, 2, 3, 5, 6, 7, 8, 9, 10)
like image 107
som-snytt Avatar answered Nov 09 '22 06:11

som-snytt


The problem is with the semi-mutable collection you chose, since an Array's elements may be mutated but its size cannot be changed. You really want a Buffer which already provides a "remove(index)" method.

Assuming you already have an Array, you can easily convert it to and from a Buffer in order to perform this operation

def remove(a: Array[String], i: index): Array[String] = {
  val b = a.toBuffer
  b.remove(i)
  b.toArray
} 
like image 28
swartzrock Avatar answered Nov 09 '22 06:11

swartzrock