【问题标题】:Understanding `andThen`理解“然后”
【发布时间】:2019-05-23 21:46:36
【问题描述】:

遇到了andThen,但是没看懂。

为了进一步了解它,我阅读了 Function1.andThen 文档

def andThen[A](g: (R) ⇒ A): (T1) ⇒ A

mm 是一个MultiMap 实例。

scala> mm
res29: scala.collection.mutable.HashMap[Int,scala.collection.mutable.Set[String]] with scala.collection.mutable.MultiMap[Int,String] = 
                    Map(2 -> Set(b) , 1 -> Set(c, a))

scala> mm.keys.toList.sortWith(_ < _).map(mm.andThen(_.toList))
res26: List[List[String]] = List(List(c, a), List(b))

scala> mm.keys.toList.sortWith(_ < _).map(x => mm.apply(x).toList)
res27: List[List[String]] = List(List(c, a), List(b))

注意 - 来自DSLs in Action的代码

andThen 强大吗?基于这个例子,它看起来像mm.andThen 去糖到x =&gt; mm.apply(x)。如果andThen有更深层次的含义,那我还没看懂。

【问题讨论】:

    标签: scala function-composition


    【解决方案1】:

    andThen 只是函数组合。给定一个函数f

    val f: String => Int = s => s.length
    

    andThen 创建一个新函数,该函数应用 f 后跟参数函数

    val g: Int => Int = i => i * 2
    
    val h = f.andThen(g)
    

    h(x) 则为 g(f(x))

    【讨论】:

    • 写作的好处在哪里:g(f(x)) ?
    • @StefanKunze 也许是因为val h = first andThen second andThen third andThen fourthval h : String =&gt; Int = x =&gt; fourth(third(second(first(x)))) 更容易写:) 有趣的事实:F# 有&gt;&gt; 运算符用于从左到右的函数组合,所以你可以还可以节省一些击键次数。
    • f.andThen(g)(x) 比写g(f(x))没有优势。但是写h(f andThen g) 比写另一个函数def fAndThenG(x:String) = f(g(x)) 来调用h(fAndThenG) 有一个的优势。也就是说,如果您想将组合函数作为参数传递,andThen 允许您快速且匿名地这样做。
    • 你为什么使用val 而不是def 函数fg
    • @StefanKunze 这根本不是语法糖。这是一个功能。语法糖是语法,它可以做其他语法可以做的事情。函数是具体的实现,而不是语法。 Scala 没有用于函数组合的语法(只是函数应用程序)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-30
    • 2016-06-14
    • 2015-10-28
    • 2013-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多