Advertisement
Guest User

Untitled

a guest
Feb 27th, 2015
180
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.01 KB | None | 0 0
  1.  
  2.   // EXERCISE 5: Complete the following definition, so that "getAndSet" is a (stateless) function
  3.   // that when invoked with integer n returns a pair of functions (that share state) that allow
  4.   // reading and writing a var that is initialized with integer n.  The first function in the pair
  5.   // should be the reader.  The second function in the pair should be the writer.  For example, the
  6.   // following expression should return 5: { val (get, set) = getAndSet (5); set (10); get () }
  7.   // Multiple calls to "getAndSet" should yield independent pairs, i.e., the first pair returned
  8.   // should not share any state with the second pair returned.
  9.   val getAndSet : Int => (() => Int, Int => Unit) = {
  10.     // TODO: Complete the definition.
  11.  
  12.     (n) =>
  13.     {
  14.       var x = n
  15.       val get : () => Int = {
  16.         () => {
  17.           val ret = x
  18.           ret
  19.         }
  20.         }
  21.  
  22.       val set : (Int) => Unit = {
  23.         (setterVal) => {
  24.           x = setterVal
  25.         }
  26.       }
  27.       (get, set)
  28.     }
  29.  
  30.   }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement