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