gpt4 book ai didi

Scala "<-"用于理解

转载 作者:行者123 更新时间:2023-12-03 11:03:43 24 4
gpt4 key购买 nike

我发现 Scala 总是对任何事情都有“自然的解释”。总是像“哦,但这只是在这个和那个对象上使用这个和那个参数调用的函数”。从某种意义上说,没有什么是真正的编译器魔法,正如我们从其他语言中所知道的那样。

我的问题在 <- 以下代码中使用的运算符:

for(i <- 0 to 10) println(i)

在这个例子中,我可以看到它被重写为:
0.to(10).foreach((i:Int)=>println(i))

但这并不能解释 进入 foreach 函数内的匿名函数。在你写 的地方我 它不是一个对象,也不是一个声明的变量。那么它是什么,它是如何被转移到 foreach 内部的呢?

我的猜测是我终于发现了一些实际上是编译器魔法的东西

谢谢你的时间。

为了澄清,我的问题是: <- 运算符如何在第一行代码中工作,因为 i 不是可以作为函数调用的对象。

最佳答案

为了补充 Dave 的答案,这里是 Scala 语言规范中“理解”的翻译模式:

A comprehension for (enums) yield e evaluates expression e for each binding generated by the enumerators enums. An enumerator sequence always starts with a generator; this can be followed by further generators, value definitions, or guards.

A generator p <- e produces bindings from an expression e which is matched in some way against pattern p. A value definition val p = e binds the value name p (or several names in a pattern p) to the result of evaluating the expression e. A guard if e contains a boolean expression which restricts enumerated bindings.

The precise meaning of generators and guards is defined by translation to invocations of four methods: map, filter, flatMap, and foreach. These methods can be implemented in different ways for different carrier types.

The translation scheme is as follows. In a first step, every generator p <- e, where p is not irrefutable (§8.1) for the type of e is replaced by

 p <- e.filter { case p => true; case _ => false }

Then, the following rules are applied repeatedly until all comprehensions have been eliminated.

  • A for-comprehension for (p <- e) yield e0 is translated to e.map { case p => e0 }.

  • A for-comprehension for (p <- e) e0 is translated to e.foreach { case p => e0 }.

  • A for-comprehension for (p <- e; p0 <- e0 . . .) yield e00, where . . . is a (possibly empty) sequence of generators or guards, is translated to:
    e.flatMap { case p => for (p0 <- e0 . . .) yield e00 }.

  • A for-comprehension for (p <- e; p0 <- e0 . . .) e00 where . . . is a (possibly empty) sequence of generators or guards, is translated to:
    e.foreach { case p => for (p0 <- e0 . . .) e00 } .

  • A generator p <- e followed by a guard if g is translated to a single generator:
    p <- e.filter((x1, . . . , xn) => g )
    where x1, . . . , xn are the free variables of p.

  • A generator p <- e followed by a value definition val p0 = e0 is translated to the following generator of pairs of values, where x and x0 are fresh names:

    val (p, p0) <- 
    for(x@p <- e) yield { val x0@p0 = e0; (x, x0) }

关于Scala "<-"用于理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3754089/

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