2017-02-26 81 views
0

我在做什麼錯?舉例來說,這應該返回10:Scala無狀態函數

{ val (get, set) = getAndSet (5); set (10); get() } 

val getAndSet : Int => (() => Int, Int => Unit) = { 
var s : Int = 0 
val get :() => Int =() => { 
    val z = s; 
    s = s + 1; 
    z 
} 
val set : Int => Unit = (x:Int) => { 
    s = x 
} 
x => (get, set) 
} 

回答

0

夫婦的錯誤:

  • n不存在,則可能意味着s
  • 最後一行應該是x => (get, set),儘管您沒有以任何方式使用x

這裏是你的代碼的至少修改過的版本。由於你沒有使用x的作品

val getAndSet: Int => (() => Int, Int => Unit) = { 
    var s: Int = 0 
    val get :() => Int =() => { 
    val z = s; 
    s = s + 1; 
    z 
    } 
    val set : Int => Unit = (x:Int) => { 
    s = x 
    } 
    x => (get, set) 
} 

,則可以選擇做

val getAndSet: Int => (() => Int, Int => Unit) = _ => { 
    var s: Int = 0 
    val get :() => Int =() => { 
    val z = s; 
    s = s + 1; 
    z 
    } 
    val set : Int => Unit = (x:Int) => { 
    s = x 
    } 
    (get, set) 
} 
+0

我的道歉,我沒有看到我的輸入錯誤。我的代碼編譯雖然但它沒有通過測試。我也認爲「s = s + 1;」應該是平等的,我怎麼會把它變成平等?它會像「s.Equal(s + 1)」? – yeny314