我想链接一堆过滤器,但不希望与创建多个列表相关的开销。
type StringFilter = (String) => Boolean
def nameFilter(value: String): StringFilter =
(s: String) => s == value
def lengthFilter(length: Int): StringFilter =
(s: String) => s.length == length
val list = List("Apple", "Orange")
问题是这会在每个过滤器之后建立一个列表:
list.filter(nameFilter("Apples")).filter(lengthFilter(5))
// list of string -> list of name filtered string -> list of name and length filtered string
我想要:
// list of string -> list of name and length filtered string
我找出运行时需要哪些过滤器,因此我必须动态添加过滤器。
// Not sure how to implement add function.
val filterPipe: StringFilter = ???
// My preferred DSL (or very close to it)
filterPipe.add(nameFilter("Apples")
filterPipe.add(lengthFilter(5))
// Must have DSL
list.filter(filterPipe)
我该如何实现
filterPipe
?是否有某种方法可以在 filterPipe(它本身就是一个 StringFilter)中递归地将过滤条件和过滤条件放在一起?
最佳答案
您可以使用 withFilter
:
list.withFilter(nameFilter("Apples")).withFilter(lengthFilter(5))...
关于scala - 无开销的链式 Scala 过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28638060/