Scala: remove first column (first element in each row)

2k Views Asked by At

Given an var x: Array[Seq[Any]], what would be the most efficient (fast, in-place if possible?) way to remove the first element from each row?

I've tried the following but it didn't work - probably because of immutability...

  for (row <- x.indices)
    x(row).drop(1)
2

There are 2 best solutions below

10
Dan Getz On BEST ANSWER

First off, Arrays are mutable, and I'm guessing you're intending to change the elements of x, rather than replacing the entire array with a new array object, so it makes more sense to use val instead of var:

val x: Array[Seq[Any]]

Since you said your Seq objects are immutable, then you need to make sure you are setting the values in your array. This will work:

for (row <- x.indices)
  x(row) = x(row).drop(1)

This can be written in nicer ways. For example, you can use transform to map all the values of your array with a function:

x.transform(_.drop(1))

This updates in-place, unlike map, which will leave the old array unmodified and return a new array.

EDIT: I started to speculate on which method would be faster or more efficient, but the more I think about it, the more I realize I'm not sure. Both should have acceptable performance for most use cases.

0
Jade Tang On

this would work

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

scala> x map(_.drop(1))
res0: Array[List[Int]] = Array(List(2, 3), List(2, 3))