用其他元素替换某些元素的每个匹配项

时间:2010-11-13 03:49:46

标签: list scala

什么是最好的Scala方法从某些列表中替换每个元素x出现的其他元素y?这就是我现在正在做的事情:

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

有更简洁的方法吗?感谢。

3 个答案:

答案 0 :(得分:9)

list.map(i => if (i==x) y else i)
这是怎么回事?

答案 1 :(得分:7)

如果您需要做很多事情,可以编写一个实用功能:

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

这将允许你写

list map replace(x, y)

或者,对于中缀语法:

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)

另一种解决方案是使用Map:

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

使用效用函数:

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)

答案 2 :(得分:2)

您可以创建替换的自定义方法:

class RichIterable[E] (col: Iterable[E]) {
    def replace(pairs: (E, E)*): Iterable[E] = col map {
        a => pairs.find(_._1 == a) match {
            case None => a
            case Some(p) => p._2
        }
    }
}

object RichIterable {
    implicit def iterable2RichIterable[A](col: Iterable[A]) = 
        new RichIterable(col)
}

更换元素应该很容易:

scala> import RichIterable._
import RichIterable._
scala> List(1, 2, 3, 4, 5, 4, 3, 4, 7).replace(3 -> 30, 4 -> 40)
res1: Iterable[Int] = List(1, 2, 30, 40, 5, 40, 30, 40, 7)