英文:
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: () => Int = {
//def count(): Int
var next = 0
() => {
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论