【问题标题】:Why doesn't Function2 have an andThen method?为什么 Function2 没有 andThen 方法?
【发布时间】:2014-03-07 22:56:45
【问题描述】:

为什么 andThen 在 Scala 中只存在于单参数函数?

以下代码有效:

val double = (x: Int) => x * 2
val timesFour = double andThen double

但是为什么多参数函数没有andThen 方法呢?

val multiply = (x: Int, y: Int) => x * y
val multiplyAndDouble = multiply andThen double

<console>:10: error: value andThen is not a member of (Int, Int) => Int

添加这个方法当然是微不足道的。标准库中省略了它有什么原因吗?

【问题讨论】:

  • 在执行一个函数后你不能返回一个以上的“东西”,那么你将如何为你的函数multiply提供2个参数?
  • 您可以缩小差距,但将tupled 应用于FunctionN(对于N 大于1​​)并得到一个Function1 TupleN.
  • @vptheron 我说的是另一种方式。应用Function2,然后应用以Function1 返回的single 结果。
  • @senia 感谢您的链接。

标签: scala function-composition


【解决方案1】:

我无法解释为什么Function2 不提供和andThen,但是Scalaz 为各种arities 的函数定义了Functor 实例,其中map 等效于andThen,这意味着您可以编写

val multiplyAndDouble = multiply map double

【讨论】:

    【解决方案2】:

    我刚刚注意到使用以下方法很容易解决:

    val multiplyAndDouble = multiply.tupled andThen double
    val res = multiplyAndDouble(1, 3) // res = 6
    

    【讨论】:

      【解决方案3】:

      这里有一个类似的问题: Scala API 2.10.*: Function2.andThen what happened to?,但也没有答案。在我看来这是可能的。这是 Scala 2.11.1 的工作示例:

      object TestFunction2 {
      
        def main(args: Array[String]): Unit = {
          val double = (x: Int) => x * 2
          val timesFour = double andThen double
          println(timesFour(2)) // prints 8
      
          val multiply = (x: Int, y: Int) => x * y
          val multiplyAndDouble = multiply andThen double
          println(multiplyAndDouble(1, 3)) // prints 6
        }
      
        implicit def toFunc2(function2: Function2[Int, Int, Int]): Func2[Int, Int, Int] = {
          new Func2[Int, Int, Int] {
            def apply(v1: Int, v2: Int): Int = function2(v1, v2)
          }
        }
      }
      
      trait Func2[-T1, -T2, +R] extends Function2[T1, T2, R] {
        def andThen[A](g: R => A): (T1, T2) => A = { (x, y) => g(apply(x, y)) }
      }
      

      【讨论】:

        【解决方案4】:

        写theons答案的另一种方法是使用:

        val multiplyAndDouble = double compose multiply.tupled
        val result = multiplyAndDouble(2, 6) // res 24
        

        【讨论】:

          猜你喜欢
          • 2018-04-03
          • 2019-01-21
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-07-16
          • 2015-05-01
          相关资源
          最近更新 更多