How to return a function in scala

前端 未结 5 1050
忘了有多久
忘了有多久 2021-02-02 14:31

How can I return a function side-effecting lexical closure1 in Scala?

For instance, I was looking at this code sample in Go:

5条回答
  •  醉酒成梦
    2021-02-02 14:54

    While we're sharing cool implementations of the fibonacci function that are only tangentially related to the question, here's a memoized version:

    val fib: Int => BigInt = {                         
       def fibRec(f: Int => BigInt)(n: Int): BigInt = {
          if (n == 0) 1 
          else if (n == 1) 1 
          else (f(n-1) + f(n-2))                           
       }                                                     
       Memoize.Y(fibRec)
    }
    

    It uses the memoizing fixed-point combinator implemented as an answer to this question: In Scala 2.8, what type to use to store an in-memory mutable data table?

    Incidentally, the implementation of the combinator suggests a slightly more explicit technique for implementing your function side-effecting lexical closure:

    def fib(): () => Int = {
       var a = 0
       var b = 1
       def f(): Int = {
          val t = a;
          a = b
          b = t + b
          b
      }
      f
    }
    

提交回复
热议问题