gpt4 book ai didi

scala - Scala 中集合的终端函数

转载 作者:行者123 更新时间:2023-12-02 07:33:23 25 4
gpt4 key购买 nike

假设我们有一个包含一些 int 值(正值和负值)的列表,并且我们的任务是仅将正值加倍。这是产生所需结果的片段:

val list: List[Int] = ....

list.filter(_ > 0).map(_ * 2)

到目前为止一切顺利,但如果列表非常大,大小为 N 怎么办。程序是否在 filter 函数上迭代 N 次,然后在 map 函数上迭代 N 次?

scala 如何知道何时循环遍历列表并应用所有过滤和映射内容?如果我们按标识函数(例如去除重复项)和应用映射函数对原始列表进行分组,结果(就列表遍历而言)是什么?

最佳答案

Does the program iterates N times on filter function and then N times on map function?

是的。使用 View 使对集合的操作变得惰性。例如:

val list: List[Int] = ...
list.view.filter(_ > 0).map(_ * 2)

How does scala know when it's time to go through the list in cycle and apply all the filtering and mapping stuff?

当使用 View 时,它会在你真正去使用物化值时计算值:

val x = list.view.filter(_ > 0).map(_ * 2)
println(x.head * 2)

这仅在调用 head 时应用过滤器和 map 。

关于scala - Scala 中集合的终端函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19601062/

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