理解`andThen`

Kev*_*ith 19 scala function-composition

我遇到过andThen,但没有正确理解它.

为了进一步研究,我阅读了Function1.andThen 文档.

def andThen[A](g: (R) ? A): (T1) ? A
Run Code Online (Sandbox Code Playgroud)

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))
Run Code Online (Sandbox Code Playgroud)

注 - 来自行动中的DSL的代码

andThen强大的?基于这个例子,看起来像mm.andThen去糖x => mm.apply(x).如果有更深刻的含义andThen,那么我还没有理解它.

Lee*_*Lee 25

andThen只是功能组合.给定一个功能f

val f: String => Int = s => s.length
Run Code Online (Sandbox Code Playgroud)

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

val g: Int => Int = i => i * 2

val h = f.andThen(g)
Run Code Online (Sandbox Code Playgroud)

h(x) 那么 g(f(x))

  • 将`f.andThen(g)(x)`写在`g(f(x))`上有_no_优势.但是编写`h(f andThen g)`而不必编写另一个函数`def fAndThenG(x:String)= f(g(x))`以便你可以调用`h(fAndThenG)`是一个优点.也就是说,如果你想将组合函数作为参数传递,`andThen`允许你快速匿名地执行. (9认同)
  • 有利于写作:g(f(x))? (3认同)
  • 为什么你对函数`f`和`g`使用`val`而不是`def`? (3认同)
  • @StefanKunze也许是因为写'val h = first andThen second更容易写第三个和第四个`比例如`val h:String => Int = x =>第四个(第三个(第二个(第一个(x)))) `:)有趣的事实:F#有从左到右的函数组合的`>>运算符,所以你也可以节省一些键击. (2认同)