scala - 无开销的链式 Scala 过滤器

标签 scala

我想链接一堆过滤器,但不希望与创建多个列表相关的开销。

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/

相关文章:

java - play框架2.6 ws无法解析

Scala Play 在表单中上传文件

scala - 如何将Scala Map转换为部分函数

scala - Scala中的家庭多态性

scala - 我如何在 Scala 中实现 Kafka Consumer

scala - 在 Play 2.1 中,使用什么代替已弃用的 PushEnumerator

scala - logback 中的过滤标记

scala - C++ typeid 的 Scala 等价物是什么?

scala - 如何使用 SBT 仅运行单个 Spec2 规范?

scala - TreeMap 和 TreeSet 都创建了一个新的空化身 TreeMap.empty、TreeSet.empty。这可以修复吗?