Scala newbie trying to implement a method named "counter" whose method signature is below.
The method should be a stateless function so that when it is invoked with integer n, it returns a stateful function. This stateful function should return n when it is first called, then n + 1, then n + 2, etc.
The counters must be independent such that running counter(1) twice yields two functions that do not interfere with each other's state.
Below is what I have so far:
val counter : Int => () => Int = {
// Complete definition below.
var count = 0
n: Int => () => {
var returnVal = n + count
count = count + 1
returnVal
}
}
An example of how counter is called:
assert ({
val k1 : () => Int = counter (1)
val k2 : () => Int = counter (2)
val r1 : Int = k1 ()
val r2 : Int = k1 ()
val r3 : Int = k2 ()
val r4 : Int = k2 ()
val r5 : Int = k2 ()
val r6 : Int = k1 ()
(r1, r2, r3, r4, r5, r6)
} === (1, 2, 2, 3, 4, 3)
)
When running the assert, my implementation of counter returns (1, 2, 4, 5, 6, 6).
I believe this is due to k1 and k2 both pointing to the same count variable. However, I can't figure out how I would provide k1 and k2 their own separate count variable so that they "do not interfere with each other's state", as per the requirements.
Am I on the right track? Any guidance would be most appreciated.