如何计算Scala中的迭代次数以便于理解Scala?
我使用a来理解流,我想知道需要多少次迭代才能得到最终结果 代码:如何计算Scala中的迭代次数以便于理解Scala?,scala,functional-programming,for-comprehension,Scala,Functional Programming,For Comprehension,我使用a来理解流,我想知道需要多少次迭代才能得到最终结果 代码: var count = 0 for { xs <- xs_generator x <- xs count = count + 1 //doesn't work!! if (x prop) yield x } var计数=0 为了{ xs编辑:如果您不想只返回第一项,而是返回整个解决方案流,请查看第二部分 编辑-2:附加了zipWithIndex的较短版本 你想做什么还不完全清楚。对我来说
var count = 0
for {
xs <- xs_generator
x <- xs
count = count + 1 //doesn't work!!
if (x prop)
yield x
}
var计数=0
为了{
xs编辑:如果您不想只返回第一项,而是返回整个解决方案流,请查看第二部分
编辑-2:附加了zipWithIndex
的较短版本
你想做什么还不完全清楚。对我来说,你似乎想在一系列的列表中找到一些东西,并额外保存选中元素的数量
如果这是你想要的,考虑这样做:
/** Returns `x` that satisfies predicate `prop`
* as well the the total number of tested `x`s
*/
def findTheX(): (Int, Int) = {
val xs_generator = Stream.from(1).map(a => (1 to a).toList).take(1000)
var count = 0
def prop(x: Int): Boolean = x % 317 == 0
for (xs <- xs_generator; x <- xs) {
count += 1
if (prop(x)) {
return (x, count)
}
}
throw new Exception("No solution exists")
}
println(findTheX())
// prints:
// (317,50403)
请注意{…}
部分。对于-理解,中可能发生的事情数量有限:
- 生成器(
x什么是“prop”有些谓词?是的,只是为了让我通过一个流循环来构建一个更小的新流,我想知道我检查了多少个元素。听起来像是一个用于<代码>的工作。ZIPWORKEDITION < /Cord> @ USENULCT:固定的,它是var。@SethTisue我添加了一个zipWithIndex
-版本。现在我注意到你不是OP,我不知道该说什么,因为否则我建议你只使用zipWithIndex
版本;)老实说:不,我没有考虑<代码> ZIPWORD索引,因为我完全专注于使用OP的非编译代码中的可变计数器来最笨拙地编写它的任务。如果它是我为自己编写的一段代码,我可能会使用<代码> ZIPWORD索引< /代码>而不考虑它。当然,请尝试在这里推广最佳实践,而不是可变计数器。;)谢谢!
val xs_generator = Stream.from(1).map(a => (1 to a).toList)
var count = 0
def prop(x: Int): Boolean = x % 317 == 0
val xsWithCounter = for {
xs <- xs_generator;
x <- xs
_ = { count = count + 1 }
if (prop(x))
} yield (x, count)
println(xsWithCounter.take(10).toList)
// prints:
// List(
// (317,50403), (317,50721), (317,51040), (317,51360), (317,51681),
// (317,52003), (317,52326), (317,52650), (317,52975), (317,53301)
// )
val xsWithCounter =
xs_generator.flatten.zipWithIndex.filter{x => prop(x._1)}