gpt4 book ai didi

scala - 如何将转换链的结果通过管道传递给函数?

转载 作者:行者123 更新时间:2023-12-04 07:54:28 25 4
gpt4 key购买 nike

我想写一个转换链,最后有一个 block ,我在不使用变量的情况下对结果集合做一些事情。
集合上是否有一个高阶函数,它只提供调用它所提供函数的集合?

Query( ... )
.map { ... }
.filter { ... }
.combinations(2)
.pipeTo { col =>
...
consolidate(col)
}

当然,对于单个函数调用,可以这样做:
consolidate(
Query()
.map { ... }
.filter { ... }
.combinations(2)
)

但前者对我来说更自然,并允许例如用于轻松注入(inject)一些条件。

我一直在使用的解决方法是在末尾放置一个匹配子句:
Query()
.map { ... }
.filter { ... }
.combinations(2)
match { case lst =>
...
consolidate(lst)
}

但由于这种模式经常发生,我想知道写这个的惯用方式是什么。

最佳答案

也许最惯用的方法是使用所谓的 Pimp My Library Pattern ,它允许通过隐式类转换向任何类添加扩展方法。

例如,添加 consolidate方法 List s,你可以写:

object ListExtensions {
implicit class ConsolidatableList[T](val lst: List[T]) extends AnyVal {
def consolidate = ??? // Do whatever you want with the List lst
}
}

import ListExtensions._

List(1,2,3)
.map(x => x * x)
.consolidate

如果您真的希望能够在链中的任意对象上调用任意函数,您甚至可以像在 F# 中那样定义“管道”运算符:
object Extensions {
implicit class PipelineExtension[T](val obj: T) extends AnyVal {
def |>[S](f: T => S): S = f(obj)
}
}

import Extensions._

List(1,2,3)
.map(x => x * x)
.|> (consolidate)

Query( ... )
.map { ... }
.filter { ... }
.combinations(2)
.|> { col =>
...
consolidate(col)
}
|>运算符的行为类似于 pipeTo您定义的方法。

基本上,这是通过使用您定义的各种扩展方法创建从您的类型到类型的隐式转换来工作的。 AnyVal使扩展类成为一个值类,因此它的使用几乎没有运行时成本。

关于scala - 如何将转换链的结果通过管道传递给函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20309219/

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