Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing every occurrence of some element by some other element

Tags:

list

scala

What is the best Scala way to replace from some list every occurrence of element x by some other element y? This is what I am doing right now:

list map { 
  case `x` => y
  case a => a
}

Is there more concise way available? Thanks.

like image 979
Greg Avatar asked Dec 03 '22 04:12

Greg


2 Answers

list.map(i => if (i==x) y else i)

how about this?

like image 199
DarrenWang Avatar answered Dec 18 '22 09:12

DarrenWang


If you need to do this a lot, you might write a utility function:

def replace[T](x: T, y: T) = (i: T) => if (i == x) y else i

This would allow you to write

list map replace(x, y)

Or, for infix syntax:

class ReplaceWith[T](x: T) {
   def replaceWith(y: T) = (i: T) => if (i == x) y else i
}
object ReplaceWith {
   implicit def any2replaceWith[T](x: T) = new ReplaceWith(x)
}

// now you can write
list map (x replaceWith y)

Another solution is to use a Map:

list map Map(x -> y).withDefault(identity)

With a utility function:

scala> def replace[T](pairs: (T, T)*) = Map(pairs: _*).withDefault(identity)
replace: [T](pairs: (T, T)*)scala.collection.immutable.Map[T,T]

scala> List(1,2,3) map replace(1 -> -1, 3 -> 4)
res0: List[Int] = List(-1, 2, 4)
like image 29
Aaron Novstrup Avatar answered Dec 18 '22 11:12

Aaron Novstrup