Scala 如何防止作为参数传递的函数求值?
MyScala 如何防止作为参数传递的函数求值?,scala,anonymous-function,Scala,Anonymous Function,Myaddvf函数根据value\u name键将added参数添加到映射中的值存储中 我希望看到打印出来的“你还没有煮咖啡”和 println(值(“咖啡中的糖”)) 是1 只有当值(“coffee”)为>=1时,才能调用addvf(“coffee中的糖”),如readvf函数所示。相反,这个addvf被称为它的声明 如果我在addvf前面加上()=>,那么操作(“向咖啡中添加糖”)()不会返回任何结果 如何防止对作为参数传递的函数进行求值 import scala.collection.
addvf
函数根据value\u name
键将added
参数添加到映射中的值存储中
我希望看到打印出来的“你还没有煮咖啡”和
println(值(“咖啡中的糖”))
是1
只有当值(“coffee”)
为>=1时,才能调用addvf(“coffee中的糖”)
,如readvf
函数所示。相反,这个addvf被称为它的声明
如果我在addvf前面加上()=>
,那么操作(“向咖啡中添加糖”)()
不会返回任何结果
如何防止对作为参数传递的函数进行求值
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!
}
尝试将addvf定义为
def addvf(value_name: String, added:Int, f:() =>Unit): ()=>Unit = () => {
val v = values(value_name)
values(value_name) = v + added
f()
}
顺便说一句,这里你真正需要的是一个状态单子)参见以供参考)这太令人困惑了——你能把它归结为创建你不想要的行为的最简单的例子吗?