在Scala中迭代时理解takeWhile终止条件
我很难理解为什么这段代码似乎提前终止:在Scala中迭代时理解takeWhile终止条件,scala,Scala,我很难理解为什么这段代码似乎提前终止: object intersectionDemo { val arr = Array(2, 4, 7, 8, 12, 20) val arr2 = Array(3, 4, 8, 9, 11, 20) Iterator.iterate((arr, arr2, List[Int]())) { case (one, two, res) => if (one.head == two.head) (one.tail
object intersectionDemo {
val arr = Array(2, 4, 7, 8, 12, 20)
val arr2 = Array(3, 4, 8, 9, 11, 20)
Iterator.iterate((arr, arr2, List[Int]())) {
case (one, two, res) =>
if (one.head == two.head)
(one.tail, two.tail, one.head :: res)
else if (one.head > two.head)
(one, two.tail, res)
else
(one.tail, two, res)
}.takeWhile { case (a, b, _) => a.nonEmpty && b.nonEmpty }
.toList.last._3.reverse
}
它返回List(4,8)
,尽管它应该返回List(4,8,20)
,如果我在这里检查第一个或第二个数组:。\u1
或。\u2
我得到数组(20)
。我知道还有其他方法可以解决两个数组的交集问题,我只是有点困惑,为什么最后一个元素没有被插入
我的猜测是,它看到one.tail
和two.tail
是空的
并终止了迭代,但是one.head
不应该仍然插入?想想看。(我正在使用List
语法来演示Array
状态,但您明白了。)
20
在1
和2
为空时插入,因此如果takeWhile
都为空,则尚未插入
如果您将其更改为.dropWhile{…}.next.\u 3.reverse
,则您将获得所需的结果
// 20::Nil 20::Nil (Nil, Nil, 20 :: 8 :: 4 :: Nil)
if (one.head == two.head) (one.tail, two.tail, one.head :: res)