2015-04-12 28 views

回答

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來測試它)

+0

如果零比B中的元素多,則零保留,如果小於B中的元素,則只使用B中的第一個值。是的,似乎迭代器不起作用。 – codez

+0

已更新爲處理B元素耗盡 –

8

你可以在這裏使用map,通過更換具有b下一個元素全部爲0(通過轉換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) 
+0

不錯,謝謝! – codez

2

如果你想看看尾遞歸,那麼這適合你。

@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) 

如果一個元素都小於B,則,

val A = Seq(1, 0) 
val B = Seq(8, 9, 10) 
scala> f(A,B) 
res2: Seq[Int] = List(1, 8) 
相關問題