【问题标题】:Scala API 2.10.*: Function2.andThen what happened to?Scala API 2.10.*:Function2.and 然后发生了什么?
【发布时间】:2013-08-03 23:34:25
【问题描述】:

我正在阅读 Joshua Suereth 所著的《Scala in Depth》,这本书是我为明确确定作者的能力而购买的。我在第 3 页,经过一堆拼写错误和不连贯的格式(好吧,我已经容忍了这些错误),我偶然发现了以下关于解决一个非常简单场景的函数式方法的示例。

trait Cat
trait Bird
trait Catch
trait FullTummy

def catch(hunter: Cat, prey: Bird): Cat with Catch
def eat(consumer: Cat with Catch): Cat with FullTummy

val story = (catch _) andThen (eat _)
story(new Cat, new Bird)

我谨慎地举了这个例子,前提是它显然是一个蓝图(没有定义具体的方法......)......«catch»显然是另一个错字,只要它是一个保留字......CatBird不可实例化......

...但是,尽管示例质量很差,但我不能认为根据函数组合定义的 «story» val(andThencompose 的«reverse-associative»)是另一个意外错误,前提是它是示例的核心

实际上,该示例无法在我的本地 Scala 版本 (2.10.1) 上编译,并且在可用的最新版本 (2.10.2) 上也没有记录。

毫无疑问它的用处和它的实现很容易完成(跟随):

trait Function2ex[-T1, -T2, +R] extends Function2[T1, T2, R] {
  def andThen[A](g: R => A): (T1, T2) => A = { (x, y) => g(apply(x, y)) }
} 

在对 API 进行简短审查后,我发现 andThen 仅受 Function1 支持,并且据说从 Function2 消失到 Function22 所以,问题是:

目前支持 andThencompose with Function* of arity 大于 1 的成语是什么?

【问题讨论】:

    标签: api scala function-composition


    【解决方案1】:

    我根本不明白那个例子的去向,但这里有一些在 scala 2.10.2 中编译的代码。

    trait Cat
    trait Bird
    trait Catch
    trait FullTummy
    
    def `catch`(hunter: Cat, prey: Bird): Cat with Catch = ???
    def eat(consumer: Cat with Catch): Cat with FullTummy = ???
    
    val story = (`catch` _).tupled andThen (eat _)
    story(new Cat with Catch, new Bird {})
    

    我不得不引用catch,因为它是一个保留字,并且是Function2的元组。

    【讨论】:

    • 能否请您详细说明元组。为什么你必须使用它(我知道它不能正常工作,但为什么我们必须对它进行元组处理,因为 eat 不接受元组而不是单个参数“消费者”)?它到底在做什么
    • 我们必须对它进行元组处理,因为(`catch` _) 是一个Function2,它没有andThen 方法。而返回类型 (Cat with Catch) 必须与 eat 的参数类型匹配。
    • 所以我们实际上使用元组将其转换为 Function1 以获得“andThen”函数,对吗?
    • 是的。我不太确定为什么 Function2 没有自己的 andThen 方法。
    猜你喜欢
    • 1970-01-01
    • 2018-11-12
    • 1970-01-01
    • 2011-10-19
    • 1970-01-01
    • 2014-03-16
    • 2012-09-02
    • 2011-12-01
    • 1970-01-01
    相关资源
    最近更新 更多