Scala和dropWhile

前端之家收集整理的这篇文章主要介绍了Scala和dropWhile前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我是HS的高级成员,也是函数式编程和 Scala的新手.我在 Scala REPL中尝试了一些构造,并需要一些返回响应的指导

//Defined a tuple

scala> val x =(2.0,3.0,1)
x: (Double,Double,Int) = (2.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,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就会删除任何值,并返回迭代器的其余部分:

Skips longest sequence of elements of this iterator which satisfy
given predicate p,and returns an iterator of the remaining elements.

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

例如,如果您选择在isInstanceOf [Double]时删除,则会收到包含单个元素1的列表:

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

猜你在找的Scala相关文章