Search code examples
scalascheme

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))))

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!


Solution

  • Do you mean

    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