Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove one element from Scala List

Tags:

scala

For example, if I have a list of List(1,2,1,3,2), and I want to remove only one 1, so the I get List(2,1,3,2). If the other 1 was removed it would be fine.

My solution is:

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

scala> myList.patch(myList.indexOf(1), List(), 1)
res7: List[Int] = List(2, 1, 3, 2)

But I feel like I am missing a simpler solution, if so what am I missing?

like image 821
Akavall Avatar asked Jun 03 '17 04:06

Akavall


People also ask

What is a SEQ in Scala?

Scala Seq is a trait to represent immutable sequences. This structure provides index based access and various utility methods to find elements, their occurences and subsequences. A Seq maintains the insertion order.

What is Scala buffer list?

Scala provides a data structure, the ListBuffer, which is more efficient than List while adding/removing elements in a list. It provides methods to prepend, append elements to a list.

How do I add elements to a Scala list?

To append or add any elements inside the list object directly we cannot do so because the list is immutable. So we can assign the elements while creating the object of the list. We can append value to the list and listBuffer.


2 Answers

surely not simpler:

def rm(xs: List[Int], value: Int): List[Int] = xs match {
  case `value` :: tail =>  tail
  case x :: tail => x :: rm(tail, value)
  case _ => Nil
}

use:

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

scala> rm(xs, 1)
res21: List[Int] = List(2, 1, 3)

scala> rm(rm(xs, 1), 1)
res22: List[Int] = List(2, 3)

scala> rm(xs, 2)
res23: List[Int] = List(1, 1, 3)

scala> rm(xs, 3)
res24: List[Int] = List(1, 2, 1)
like image 58
perreal Avatar answered Sep 17 '22 23:09

perreal


you can zipWithIndex and filter out the index you want to drop.

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

scala> myList.zipWithIndex.filter(_._2 != 0).map(_._1)
res1: List[Int] = List(2, 1, 3, 2)

The filter + map is collect,

scala> myList.zipWithIndex.collect { case (elem, index) if index != 0 => elem }
res2: List[Int] = List(2, 1, 3, 2)

To remove first occurrence of elem, you can split at first occurance, drop the element and merge back.

list.span(_ != 1) match { case (before, atAndAfter) => before ::: atAndAfter.drop(1) }

Following is expanded answer,

val list = List(1, 2, 1, 3, 2)

//split AT first occurance
val elementToRemove = 1
val (beforeFirstOccurance, atAndAfterFirstOccurance) = list.span(_ != elementToRemove)

beforeFirstOccurance ::: atAndAfterFirstOccurance.drop(1) // shouldBe List(2, 1, 3, 2)

Resource

How to remove an item from a list in Scala having only its index?

How should I remove the first occurrence of an object from a list in Scala?

like image 29
prayagupa Avatar answered Sep 17 '22 23:09

prayagupa