【问题标题】:How to specify the arguments to a function passed to a Scala map (Higher Order) Function?如何指定传递给 Scala 映射(高阶)函数的函数的参数?
【发布时间】: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


    【解决方案1】:

    你可以做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) } .
    • 第二个 -> ``` scala> val seq_xs = (Seq.fill(degree)(x)).zipWithIndex.map(exp.tupled) :14: error: missing argument方法 exp 的列表 未应用的方法仅在需要函数类型时才转换为函数。您可以通过编写 exp _exp(_,_) 而不是 exp 来明确此转换。 val seq_xs = (Seq.fill(degree)(x)).zipWithIndex.map(exp.tupled) ``
    • @BhawandeepSingh 哎呀。修复。 Try now.
    • @BhawandeepSingh 是的,该错误与此无关,它只是您代码中某处的错误。
    【解决方案2】:

    有两种方法可以做到这一点。

    首先,也许对读者来说最清楚的是,您可以解构 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)
    

    【讨论】:

    • 谢谢,我收到以下错误 -> ``` scala> val seq_xs = (Seq.fill(degree)(x)).zipWithIndex.map((exp _).tupled) java .lang.UnsupportedOperationException: empty.reduceLeft at scala.collection.LinearSeqOptimized.reduceLeft(LinearSeqOptimized.scala:139) at scala.collection.LinearSeqOptimized.reduceLeft$(LinearSeqOptimized.scala:138) at scala.collection ```
    • @BhawandeepSingh 此错误与您的问题无关。你只是在某处的空序列上调用reduceLeft
    • 谢谢,度数为0的情况下失败了。
    猜你喜欢
    • 2021-02-25
    • 2022-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多