为什么Function2没有andThen方法?

问题描述 投票:14回答:4

为什么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

当然,添加这种方法是微不足道的。它是否有理由从标准库中省略?

scala function-composition
4个回答
4
投票

我不能说为什么Function2不供应和andThen,但Scalaz定义Functor实例的各种arities函数map相当于andThen,这意味着你可以写

val multiplyAndDouble = multiply map double

1
投票

这里有一个类似的问题: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)) }
}

0
投票

我刚刚注意到以下内容很容易解决:

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

0
投票

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

val multiplyAndDouble = double compose multiply.tupled
val result = multiplyAndDouble(2, 6) // res 24
© www.soinside.com 2019 - 2024. All rights reserved.