Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is an idiomatic Scala way to "remove" one element from an immutable List?

Tags:

list

scala

I have a List, which may contain elements that will compare as equal. I would like a similar List, but with one element removed. So from (A, B, C, B, D) I would like to be able to "remove" just one B to get e.g. (A, C, B, D). The order of the elements in the result does not matter.

I have working code, written in a Lisp-inspired way in Scala. Is there a more idiomatic way to do this?

The context is a card game where two decks of standard cards are in play, so there may be duplicate cards but still played one at a time.

def removeOne(c: Card, left: List[Card], right: List[Card]): List[Card] = {
  if (Nil == right) {
    return left
  }
  if (c == right.head) {
    return left ::: right.tail
  }
  return removeOne(c, right.head :: left, right.tail)
}

def removeCard(c: Card, cards: List[Card]): List[Card] = {
  return removeOne(c, Nil, cards)
}
like image 344
Gavilan Comun Avatar asked Apr 12 '11 14:04

Gavilan Comun


People also ask

How do I remove an element from an array in Scala?

An ArrayBuffer is a mutable sequence, so you can delete elements with the usual -= , --= , remove , and clear methods.

Is Scala list immutable?

Specific to Scala, a list is a collection which contains immutable data, which means that once the list is created, then it can not be altered. In Scala, the list represents a linked list. In a Scala list, each element need not be of the same data type.

How do you delete a Scala?

Scala Map remove() method with exampleThe remove() method is utilized to remove a key from the map and return its value only. Return Type: It returns the value of the key present in the above method as argument. We use mutable map here, as remove method is a member of mutable map.


3 Answers

I haven't seen this possibility in the answers above, so:

scala> def remove(num: Int, list: List[Int]) = list diff List(num) remove: (num: Int,list: List[Int])List[Int]  scala> remove(2,List(1,2,3,4,5)) res2: List[Int] = List(1, 3, 4, 5) 

Edit:

scala> remove(2,List(2,2,2)) res0: List[Int] = List(2, 2) 

Like a charm :-).

like image 66
Antonin Brettsnajdr Avatar answered Sep 21 '22 07:09

Antonin Brettsnajdr


You could use the filterNot method.

val data = "test" list = List("this", "is", "a", "test") list.filterNot(elm => elm == data) 
like image 22
Søren Mathiasen Avatar answered Sep 19 '22 07:09

Søren Mathiasen


You could try this:

scala> val (left,right) = List(1,2,3,2,4).span(_ != 2)
left: List[Int] = List(1)
right: List[Int] = List(2, 3, 2, 4)

scala> left ::: right.tail                            
res7: List[Int] = List(1, 3, 2, 4)

And as method:

def removeInt(i: Int, li: List[Int]) = {
   val (left, right) = li.span(_ != i)
   left ::: right.drop(1)
}
like image 42
Frank S. Thomas Avatar answered Sep 20 '22 07:09

Frank S. Thomas