加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

在Scala’for’枚举器中隐含?

发布时间:2020-12-16 18:02:15 所属栏目:安全 来源:网络整理
导读:如何在for语句中引入变量(枚举器,因为它在规范中调用)是隐式的? 这是我想写的一个例子: for (implicit genNum: GenNum - NumGens(200)) { val explicitArg = // . . . funcWithImplicitGenNum(explicitArg) // -- gen passed implicitly here} 其中funcWit
如何在for语句中引入变量(枚举器,因为它在规范中调用)是隐式的?

这是我想写的一个例子:

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

其中funcWithImplicitGenNum声明如下:

def funcWithImplicitGenNum(explicitArg: Whatever)(implicit gen: GenNum) = ???

如果我正确理解规范,它不允许for的枚举器是隐式的,所以我必须这样做:

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

这种解决方法不是世界末日,但它困扰我.在我的实际程序中,我在整个地方隐式传递了几个变量,这些变量提供了发生某些事情的整体上下文. Scala的含义非常精彩:它们大大减少了代码中的混乱程度,但是调用堆栈中的深层函数可以访问该上下文信息.唯一的例外是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.

作为一种解决方法,您可以将隐式循环放在包装映射或flatMap中(当然,这不是理想的):

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.
        }
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读