斯卡拉传递函数作为参数传递给另一个函数
问题描述:
对不起这个烂摊子。我仍然在Scala中取得进展。改写所有的问题是:斯卡拉传递函数作为参数传递给另一个函数
def func1(x: Double, y: Double) = {
x+y
}
def func2(x: Double, y: Double) = {
x-y
}
def calc(f: (Double, Double) => Double, z: Int) = {
f(1,2) + z
}
//Sometimes I want to call
calc(func1(1,2), 3)
//Other times
calc(func2(1,2), 3)
,我得到这个错误:
<console>:52: error: type mismatch;
found : Double
required: (Double, Double) => Double
calc(func1(1,2), 3)
^
什么是正确的方法来调用计算()?
感谢
答
首先,你正在使用VAR的是,这是不被认为是很好的做法,如果你的地图是指使用(不想去详细了解更多信息阅读this)在课堂上的本地可以创建一个可变映射。
现在回到你的问题: 如果你希望你的函数如预期那么你应该确保doSomeComputation函数会返回一个由otherFunction有望作为输入参数,像这样
值工作def doSomeComputation(m1: Map[String, List[(String, Double)]], name: String) = {
(Map("some_key" -> List(("tuple1",1.0))), "tuple2")
}
返回类型为(图[字符串,列表[字符串,INT]],字符串)
但是它不会使你在做什么太大的意义试着去做,我可以帮助你理解你是否可以清楚地提到你想要达到的目标。
答
请注意,在calc()
正文中提供了参数f()
,即1
和2
。
def calc(f: (Double, Double) => Double, z: Int) = {
f(1,2) + z
}
因此,你不需要指定功能的任何参数的传递。
calc(func1, 3)
calc(func2, 3)
答
你需要传递函数签名f: (Map[String,List[(String, Double)]], String) => Double
而不仅仅是返回类型。下方的轻视例如:
var testMap: Map[String, List[(String, Double)]] = Map(
"First" -> List(("a", 1.0), ("b", 2.0)),
"Second" -> List(("c", 3.0), ("d", 4.0))
)
// testMap: Map[String,List[(String, Double)]] = Map(First -> List((a,1.0), (b,2.0)), Second -> List((c,3.0), (d,4.0)))
def doSomeComputation(m1: Map[String, List[(String, Double)]], name: String): Double = {
m1.getOrElse(name, List[(String, Double)]()).map(x => x._2).max
}
// doSomeComputation: (m1: Map[String,List[(String, Double)]], name: String)Double
def doSomeOtherComputation(m1: Map[String, List[(String, Double)]], name: String): Double = {
m1.getOrElse(name, List[(String, Double)]()).map(x => x._2).min
}
// doSomeOtherComputation: (m1: Map[String,List[(String, Double)]], name: String)Double
def otherFunction(f: (Map[String, List[(String, Double)]], String) => Double, otherName: String) = {
f(testMap, "First") * otherName.length
}
// otherFunction: (f: (Map[String,List[(String, Double)]], String) => Double, otherName: String)Double
println(otherFunction(doSomeComputation, "computeOne"))
// 20.0
println(otherFunction(doSomeOtherComputation, "computeOne"))
// 10.0
根据您的使用情况下,它可能是一个好主意,还通过testMap
和name
作为参数传递给otherFunction
。
这不是传递函数作为参数,而是传递函数的结果。 –
是的,你是对的 – MLeiria