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

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

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:

  1. (define count
  2. (let ([next 0])
  3. (lambda ()
  4. (let ([v next])
  5. (set! next (+ next 1))
  6. 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:

  1. 你是指
  2. ```scala
  3. val count: () => Int = {
  4. //def count(): Int
  5. var next = 0
  6. () => {
  7. val v = next
  8. next += 1
  9. v
  10. }
  11. }

吗?

  1. Functional Programming Style:
  2. ```scala
  3. FP风格的话会是
  4. ```scala
  5. def count(): Int = {
  6. def loop(next: Int, v: Int): Int = v
  7. val next = 0
  8. loop(next + 1, next)
  9. }
  1. Please note that the code is presented in a translated form, as requested.
  2. <details>
  3. <summary>英文:</summary>
  4. Do you mean
  5. ```scala
  6. val count: () =&gt; Int = {
  7. //def count(): Int
  8. var next = 0
  9. () =&gt; {
  10. val v = next
  11. next += 1
  12. v
  13. }
  14. }

?

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

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

FP style would be

  1. def count(): Int = {
  2. def loop(next: Int, v: Int): Int = v
  3. val next = 0
  4. loop(next + 1, next)
  5. }

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:

确定