【问题标题】:Why Scala implement andThen function only for Function1为什么Scala只为Function1实现andThen函数
【发布时间】:2017-08-29 06:21:54
【问题描述】:

为什么 Scala 只为 Function1 实现了方法 andThen(它只接受一个参数)。我看不出其他功能没有这种方法的任何原因。

下面我们有可以编译的合法代码:

val firstFunction: String => String = ???
val secondFunction: String => String = ???
firstFunction.andThen(secondFunction)

但这不会编译:

val firstFunction: (String,String) => String = ???
val secondFunction: String => String = ???
firstFunction.andThen(secondFunction)

【问题讨论】:

    标签: scala functional-programming


    【解决方案1】:

    我看不出其他函数没有这样的原因 方法。

    因为使用Function.tupledFunction2[String, String, String] 转换为Function1[(String, String), String] 很简单:

    firstFunction.tupled andThen secondFunction
    

    这适用于任何数量的函数。

    【讨论】:

    • 我猜 OP 会想要 Function2,而不是 Function1
    • @EduardoParejaTobes 正如答案中所述,OP 可以有一个 Function2,但如果他想使用 andThen 组合它,他将拥有匹配的数量。
    • 我会写一个答案,很难在评论中解释自己。
    【解决方案2】:

    我猜你会希望andThen 在你的firstFunction.andThen(secondFunction) 示例中返回一个Function2

    您可以轻松地将其添加到Function2(或任何其他FunctionN):

    implicit final
    class Function2MulticategoryOps[A,B,C](val f: (A,B) => C) extends AnyVal {
    
      def andThen[X](g: C => X): (A,B) => X =
        (a,b) => g(f(a,b))
    }
    

    tupled 本身并没有多大帮助:你需要像untupled这样的东西:

    // note the awful syntax for functions with domain a tuple
    implicit final
    class Untuple[A,B,C](val f: ((A,B)) => C) extends AnyVal {
    
      def untupled: (A,B) => C =
        (a,b) => f((a,b))
    }
    

    至于为什么FunctionN 类缺少这些方法,我不知道;肯定有人会加入与性能相关的事情。

    PS 如果你问我,我认为如果有 no FunctionN 类,生活会更轻松,并且几个参数的函数将只是具有域产品类型的功能;所有这些FunctionN 业务只是来自产品类别的可表示多类别的复杂和部分实现。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-25
      • 2011-07-05
      • 1970-01-01
      • 2014-03-07
      • 2017-03-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多