我有序列:
val A = Seq(1,3,0,4,2,0,7,0,6)
val B = Seq(8,9,10)
我需要一个新的序列,其中0被替换为第二个序列的值:
Seq(1,3,8,4,2,9,7,10,6)
如何在功能风格中做到这一点?
答案 0 :(得分:8)
您可以在此使用map
,将所有0替换为b
的下一个元素(通过将b
转换为迭代器,并使用next
):
val a = Seq(1,3,0,4,2,0,7,0,6)
val b = Seq(8,9,10).iterator
a.map { e => if (e == 0) b.next else e } //Seq(1,3,8,4,2,9,7,10,6)
答案 1 :(得分:4)
不确定迭代器是否真正起作用。无论如何,这是另一种选择
val A = Seq(1,3,0,4,2,0,7,0,6)
val B = Seq(8,9,10)
A.foldLeft((B, Seq[Int]())) {case ((b, r), e) =>
if (e == 0 && ! b.isEmpty) (b.tail, b.head +: r) else (b, e +: r) }
._2.reverse
//> res0: Seq[Int] = List(1, 3, 8, 4, 2, 9, 7, 10, 6)
编辑:根据评论更新,如果我们退出B的元素,则保留零
EDIT2:
模式匹配变体更整洁:
A.foldLeft((B, Seq[Int]())){case ((h +: t, r), 0) => (t, h +: r)
case ((b, r), e) => (b, e +: r)}
._2.reverse
并且基于what is proper monad or sequence comprehension to both map and carry state across?
A.mapAccumLeft(B, { case ((h +: t), 0) => (t, h)
case (b, e) => (b, e) }
(可能,我没有安装scalaz来测试它)
答案 2 :(得分:2)
如果你想看Tail Recursion,那么这适合你。
@annotation.tailrec
def f(l1: Seq[Int], l2: Seq[Int], res: Seq[Int] = Nil): Seq[Int] = {
if (l1 == Nil) res
else {
if (l1.head == 0 && l2 != Nil) f(l1.tail, l2.tail, res :+ l2.head)
else
f(l1.tail, l2, res :+ l1.head)
}
}
val A = Seq(1, 3, 0, 4, 2, 0, 7, 0, 6)
val B = Seq(8, 9, 10)
scala> f(A,B)
res0: Seq[Int] = List(1, 3, 8, 4, 2, 9, 7, 10, 6)
如果B中的元素耗尽,那么
val A = Seq(1, 3, 0, 4, 2, 0, 7, 0, 6)
val B = Seq(8, 9)
scala> f(A,B)
res1: Seq[Int] = List(1, 3, 8, 4, 2, 9, 7, 0, 6)
如果A中的元素小于B,则
val A = Seq(1, 0)
val B = Seq(8, 9, 10)
scala> f(A,B)
res2: Seq[Int] = List(1, 8)