Chain Scala Filters Without the Overhead
scala
Solution
You can use `withFilter`:
list.withFilter(nameFilter("Apples")).withFilter(lengthFilter(5))...
Problem
I want to chain a bunch of filters but do not want the overhead associated with creating multiple lists. ``` 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") ``` Problem is this builds a list after each filter: ``` list.filter(nameFilter("Apples")).filter(lengthFilter(5)) // list of string -> list of name filtered string -> list of name and length filtered string ``` I want: ``` // list of string -> list of name and length filtered string ``` I find out which filters are needed at run-time so I must add filters dynamically. ``` // 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) ``` How can I implement `filterPipe`? Is there some way to recursively AND the filter conditions together in a filterPipe (which is itself a StringFilter)?