user3160152
user3160152

Reputation: 51

Delete first element of List in Scala

I am trying to use a recursive function to go through each element in a List[Char], to check the number of occurrences of an element. I know there are easier ways and possibly even functions to do this, but would there be any way to delete just the first position of a List?

i tried using drop, and even used the following snipping but it did nothing, where test is the name of the list:

def delete(i: Int) = test.take(i) ++ test.drop((i+1));

I am trying to avoid using ListBuffer, and tried converting to Array but again to no success.

Upvotes: 0

Views: 3437

Answers (1)

Nyavro
Nyavro

Reputation: 8866

Your function is almost fine deleting item at i-th position, I would just add 'test' list as parameter to it:

scala> def delete[A](test:List[A])(i: Int) = test.take(i) ++ test.drop((i+1))
delete: [A](test: List[A])(i: Int)List[A]

scala> delete((1 to 10).toList)(3)
res0: List[Int] = List(1, 2, 3, 5, 6, 7, 8, 9, 10)

I think you trying to make some effect on 'test' using function delete but List is immutable, function delete will not produce side effect, it just returns new List

Upvotes: 1

Related Questions