【发布时间】:2019-10-03 14:51:48
【问题描述】:
我在 Scala 2.12.x 中编写了一个小型网站 Google 排名检查器,它使用页面抓取来查找给定搜索词的网站排名。我想使用 Scala 的 Stream 构建它,这是代码的控制结构模拟。但是,我找不到没有副作用的方法来重写它,换句话说,不使用任何var。
def main(args: Array[String]): Unit = {
val target = 22 // normally this would be the website domain name
val inf = 100 // we don't care for ranks above this value
var result: Option[Int] = None // <============= Side effects! how to rewrite it?
Stream.iterate(0)(_ + 10).takeWhile { i =>
// assume I'm page-scraping Google with 10 results per page
// and need to find the rank or position where the target
// website appears
for (j <- i until (i + 10)) {
// check whether the website was found
if (j == target) {
result = Some(j) // <============= Side effects! how to rewrite it?
}
}
result.isEmpty && i < inf
}.toList
println(result.getOrElse(inf))
}
基本上我希望Stream 语句直接返回result,这是目标网站出现的位置或排名。我无法逐个迭代,因为代码一次获取 10 个结果的每一页,对它们进行页面抓取并在每组 10 个结果中搜索目标网站。
【问题讨论】:
标签: scala functional-programming stream side-effects