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.
list.map(i => if (i==x) y else i)
how about this?
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With