首页 > 解决方案 > 在scala中为过滤器链接多个谓词

问题描述

我是函数式编程的新手。我想为过滤器链接多个谓词。

假设我有要过滤的名称列表...

 val names = List("cat","dog","elephant")


 //Currently I am doing like this, this is not dynamic,The list of name will come dynamically
 objects.filterSubjects(string => {
    string.endsWith("cat") ||   string.endsWith("dog") ||   string.endsWith("elephant")
  })

如何使上面的行动态化,这样我就不用写了。我想根据用户提供的名称列表创建它。

标签: scalafunctional-programmingpredicate

解决方案


您可以使用exists来检查集合中的任何值是否满足某个谓词(或每个元素的谓词)或forall检查所有值是否满足谓词 id(每个元素的谓词)。

例如,您可以像这样使用它:

val names = List("cat", "dog", "elephant")
val predicate = (s: String) => names.exists(s.endsWith _)
objects.filter(predicate)

推荐阅读