【发布时间】:2021-07-19 17:52:07
【问题描述】:
我有一个函数 f,它接受两个参数 - a:Int 和 b:Int
f (a:Int, b:Int): Int
我希望在 2 元组列表上调用 map - 这样对于列表中的每个元组 (a,b),我希望将其映射到 f(a,b)。 我将如何做? 谢谢
【问题讨论】:
标签: scala functional-programming higher-order-functions
我有一个函数 f,它接受两个参数 - a:Int 和 b:Int
f (a:Int, b:Int): Int
我希望在 2 元组列表上调用 map - 这样对于列表中的每个元组 (a,b),我希望将其映射到 f(a,b)。 我将如何做? 谢谢
【问题讨论】:
标签: scala functional-programming higher-order-functions
你可以做l.map { case (a,b) => f(a,b) }。或者一个聪明的方法:l.map((f _).tupled)
【讨论】:
scala> val seq_xs = (Seq.fill(degree)(x)).zipWithIndex.map { (a,b) => exp(a,b) } <console>:14: error: type mismatch; found : (Int, Int) => Int required: ((Int, Int)) => ? val seq_xs = (Seq.fill(degree)(x)).zipWithIndex.map { (a,b) => exp(a,b) } .
exp _ 或 exp(_,_) 而不是 exp 来明确此转换。 val seq_xs = (Seq.fill(degree)(x)).zipWithIndex.map(exp.tupled) ``有两种方法可以做到这一点。
首先,也许对读者来说最清楚的是,您可以解构 map 中的元组:
val tuples: List[(Int, Int)] = ??? // code to generate the list
tuples.map {
case (a, b) => f(a, b)
}
其次,您可以使用.tupled 将函数转换为以元组作为输入的函数。用def定义的方法必须先转成函数:
val tupledF = (f _).tupled
val tuples: List[(Int, Int)] = ??? // code to generate the list
tuples.map(tupledF)
【讨论】:
reduceLeft。