Scala是否可以像Scheme的“count”一样在函数中隐藏状态,因为它也有闭包?

huangapple go评论70阅读模式
英文:

Can scala hide state in function like scheme's "count" since it have closure too?

问题

《The scheme programming language》4th:

(define count
(let ([next 0])
(lambda ()
(let ([v next])
(set! next (+ next 1))
v))))

它使用闭包在count中隐藏状态,避免了“全局变量”。Scala似乎也支持闭包,那么在Scala中如何做到这一点呢?谢谢!

英文:

《The scheme programming language》4th:

(define count
 (let ([next 0])
  (lambda ()
   (let ([v next])
    (set! next (+ next 1))
    v))))

it hide state in the count using the closure,aovid the “global variable”。It seems scala support closure too,so how to do this in scala?Thanks!

答案1

得分: 2

Sure, here are the translated code snippets:

Scala Code:

你是指

```scala
val count: () => Int = {
//def count(): Int
  var next = 0
  () => {
    val v = next
    next += 1
    v
  }
}

吗?


Functional Programming Style:
```scala
FP风格的话会是
```scala
def count(): Int = {
  def loop(next: Int, v: Int): Int = v
  val next = 0
  loop(next + 1, next)
}

Please note that the code is presented in a translated form, as requested.

<details>
<summary>英文:</summary>

Do you mean

```scala
val count: () =&gt; Int = {
//def count(): Int
  var next = 0
  () =&gt; {
    val v = next
    next += 1
    v
  }
}

?

https://scastie.scala-lang.org/DmytroMitin/cFKKUqAjQaeFuBNos1OIvw

https://onecompiler.com/racket/3z5whfdkx

FP style would be

def count(): Int = {
  def loop(next: Int, v: Int): Int = v
  val next = 0
  loop(next + 1, next)
}

https://scastie.scala-lang.org/DmytroMitin/cFKKUqAjQaeFuBNos1OIvw/1

huangapple
  • 本文由 发表于 2023年4月17日 15:33:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/76032684.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定