Scala and dropWhile



我是HS专业的大四学生,函数式编程和Scala的新手。我在Scala REPL中尝试了一些结构,需要一些关于返回响应的指导

//Defined a tuple
scala> val x =(2.0, 3.0, 1)
x: (Double, Double, Int) = (2.0,3.0,1)
//This made sense to me.  Result is a list of values that are of type Ints
scala> x.productIterator.dropWhile(_.isInstanceOf[Double]).toList
res1: List[Any] = List(1)
**//This DID NOT make sense to me.  Why are Double values included?**
scala> x.productIterator.dropWhile(_.isInstanceOf[Int]).toList
res0: List[Any] = List(2.0, 3.0, 1)

//filter operator seems to work
scala> x.productIterator.toList.filter(x => x.isInstanceOf[Double])
res7: List[Any] = List(2.0, 3.0)

Iterator.dropWhile将删除任何值,只要它匹配所提供的谓词,并返回迭代器的剩余部分:

跳过该迭代器中满足条件的最长元素序列给定谓词p,返回剩余元素的迭代器。

您传递的谓词对于类型为Double的第一个元素失败,因此它是您实现到List[A]的整个迭代器。

如果,例如,您选择删除while isInstanceOf[Double],您将收到一个包含单个元素1的列表:

scala> x.productIterator.dropWhile(_.isInstanceOf[Double]).toList
res13: List[Any] = List(1)

最新更新