gpt4 book ai didi

Scala 和 dropWhile

转载 作者:行者123 更新时间:2023-12-05 00:54:23 24 4
gpt4 key购买 nike

我是 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 只要与提供的谓词匹配,就会删除任何值,并返回迭代器的其余部分:

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 和 dropWhile,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40178111/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com