我的addvf
函数会根据added
键将value_name
参数添加到地图中的值存储区。
我期待看到打印输出“你还没有煮咖啡”和
的打印输出
println(values("sugar_in_coffee"))
是1。
addvf("sugar_in_coffee")
只应在values("coffee")
为> = 1时调用,如readvf
函数所示。相反,这个addvf被称为声明它。
如果我使用() =>
添加addvf,则acts("add_sugar_to_coffee")()
不返回任何内容。
如何阻止评估作为参数传递的函数?
import scala.collection.mutable.HashMap
object dumbhash {
val actions = new HashMap[String, ()=>Unit]
def e(action_name: String) = {
actions(action_name)()
}
val values = new HashMap[String, Int]
values += "coffee" -> 0
values += "bread" -> 0
values += "sugar_in_coffee" -> 0
println(values("coffee"))
def readf(value_name: String, sufficient:Int, t:()=>Unit, f:() => Unit): ()=>Unit = {
if (values(value_name) >= sufficient) t else f
}
def addvf(value_name: String, added:Int, f:() =>Unit): ()=>Unit = {
val v = values(value_name)
values(value_name) = v + added
f
}
val acts = new HashMap[String, ()=> Unit]
def desc(str: String) {
println(str)
}
values("coffee") = 0
values("sugar_in_coffee") = 1
values += "made_coffee" -> 0
acts += "check_coffee" -> readf("coffee", 1,
readf("sugar_in_coffee", 1, () => desc("The coffee smells brown, like you spilled too much sugar in the cup."),
() => desc("Strong as love black coffee, waking you into this morning." )),
readf("made_coffee", 1, () => desc("You drained the cup."), () => desc("You're the type who needs coffee to make coffee")))
acts("check_coffee")()
acts += "add_sugar_to_coffee" -> readf("made_coffee", 1, addvf("sugar_in_coffee", 8, () => desc("You dump sugar into the raspberry tree coffee mug.")),
() => desc("You haven't made coffee yet"))
acts("add_sugar_to_coffee")()
println(values("sugar_in_coffee")) //returns 9!
}
答案 0 :(得分:0)
尝试将addvf定义为
def addvf(value_name: String, added:Int, f:() =>Unit): ()=>Unit = () => {
val v = values(value_name)
values(value_name) = v + added
f()
}
顺便说一句,你真正需要的是一个状态monad)请参阅http://eed3si9n.com以供参考)