gpt4 book ai didi

scala - 理解 `andThen`

转载 作者:行者123 更新时间:2023-12-03 11:54:55 24 4
gpt4 key购买 nike

我遇到了andThen ,但没有正确理解它。

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

def andThen[A](g: (R) ⇒ A): (T1) ⇒ A
mmMultiMap实例。
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 => mm.apply(x) .如果还有更深的含义 andThen ,那我还没看懂。

最佳答案

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))

关于scala - 理解 `andThen`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20292439/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com