In Scala Complete the following definition, so that \"getAndSet\" is a (stateles
ID: 3835427 • Letter: I
Question
In Scala Complete the following definition, so that "getAndSet" is a (stateless) function that when invoked with integer n returns a pair of functions (that share state) that allow reading and writing a var that is initialized with integer n. The first function in the pair should be the reader. The second function in the pair should be the writer. For example, the following expression should return 10: { val (get, set) = getAndSet (5); set (10); get () } Multiple calls to "getAndSet" should yield independent pairs, i.e., the first pair returned should not share any state with the second pair returned. val getAndSet : Int => (() => Int, Int => Unit) = {
Explanation / Answer
// should not share any state with the second pair returned. val getAndSet : Int => (() => Int, Int => Unit) = { (n:Int) => { var num = n def get : () => Int = { () => num } def set : Int => Unit = { (m:Int) => num = m } (get, set) } }
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.