0

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.

ashawley
  • 4,195
  • 1
  • 27
  • 40
user3160152
  • 51
  • 1
  • 5
  • 12
  • Consider it in different way. You need all list except `head`. For this purpose function `tail` exists. – vvg Nov 07 '15 at 21:05
  • 1
    `tail` should not be used since it's a partial function, i.e. it will throw an exception for am empty list. `Many of the functions ... like head, tail, init, and many many others fail unnecessarily.` -http://stackoverflow.com/a/23184020/409976 – Kevin Meredith Nov 07 '15 at 21:09
  • 1
    `any way to delete just the first position of a List?`. `List#drop(1)` answers this question. Why didn't it work for you? – Kevin Meredith Nov 07 '15 at 21:10
  • You're right it's much simpler with `drop` function. – vvg Nov 07 '15 at 21:13

1 Answers1

1

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

Nyavro
  • 8,806
  • 2
  • 26
  • 33