gpt4 book ai didi

scala - Scala 'for' 枚举器中的隐式?

转载 作者:行者123 更新时间:2023-12-05 01:00:38 25 4
gpt4 key购买 nike

如何在 for 中引入变量语句(一个枚举器,正如它在规范中所说的那样)隐含的?

这是我想写的一个例子:

for (implicit genNum: GenNum <- NumGens(200)) {
val explicitArg = // . . .
funcWithImplicitGenNum(explicitArg) // <-- gen passed implicitly here
}

哪里 funcWithImplicitGenNum声明如下:
def funcWithImplicitGenNum(explicitArg: Whatever)(implicit gen: GenNum) = ???

如果我正确理解规范,它不允许 for的 Enumerator 是隐式的,所以我必须这样做:
for (g <- NumGens(200)) {
implicit val genNum: GenNum = g
val explicitArg = // . . .
funcWithImplicitGenNum(explicitArg) // <-- gen passed implicitly here
}

这种解决方法不是世界末日,但它困扰着我。在我的实际程序中,我在各处隐式传递了几个变量,这些变量提供了发生某些事情的整体上下文。 Scala 的隐式在这方面非常出色:它们大大减少了代码中的困惑程度,而调用堆栈深处的函数可以访问该上下文信息。唯一的异常(exception)是 for循环:我必须用这个笨拙的技巧来定义 val等于枚举变量。

有没有办法通过 genNum隐含的?或者,如果没有,您知道我应该为 for 感到高兴的原因吗?语句不允许将其枚举器设为隐式? (通常,如果您知道语言特征的基本原理,您就会更好地了解如何“顺应语言的本质”。)

如果有帮助,这里有更多背景知识。我正在编写一个使用各种变异算子的遗传算法。变异算子不应该知道它被调用的是哪一代。但我也在收集关于突变在不同世代中如何表现的数据。数据收集代码确实需要知道它是哪一代,以及其他一些事情。因此,我显式传递了与突变相关的变量,并隐式传递了数据收集所需的变量。

最佳答案

这目前是不可能的。 Here是相关功能请求的票证。在那里,马丁·奥德斯基写道:

The problem I see is the interaction with many other things. The [implicit variable] might be a pattern – should the implicit then apply to all its variables? Then, the translation of generators in for expressions is quite involved. We'd have to specify how implicits are taken into account.



作为解决方法,您可以输入 implicit在包装中循环 mapflatMap (当然,这并不理想):
class Foo

object FooRunner {
val foos = List(new Foo, new Foo, new Foo)
def runFoo(i: Int)(implicit foo: Foo) = println(s"Foo ran $i")

def runFoos = foos.map { implicit foo =>
for(i <- (1 to 100)) {
runFoo(i) //implicit works here.
}
}
}

关于scala - Scala 'for' 枚举器中的隐式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29432825/

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