Finding elements in a scala list and also know which predicate has been satisfied

后端 未结 3 2123
时光取名叫无心
时光取名叫无心 2021-02-20 10:39

I have the following problem in scala. I have to find the first element in al list which satisfies a predicate function with two conditions in OR. The problem is that I would li

3条回答
  •  走了就别回头了
    2021-02-20 11:10

    I'd do this:

    Scala 2.8:

    def find2p[T](l: List[T], p1: T => Boolean, p2: T => Boolean) = 
      l.view.map(el => (el, p1(el), p2(el))).find(t => t._2 || t._3)
    

    Scala 2.7:

    def find2p[T](l: List[T], p1: T => Boolean, p2: T => Boolean) = 
      l.projection.map(el => (el, p1(el), p2(el))).find(t => t._2 || t._3)
    

    The view/projection ensures that the mapping will be done on-demand, instead of being applied to the whole list.

提交回复
热议问题