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

后端 未结 3 2126
时光取名叫无心
时光取名叫无心 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:30

    Here's a variant on Daniel's (and Retronym's) answer(s).

    If you just want the predicate (out of a list) that succeeded, then you can use

    def findP[T](list: Iterable[T], preds: Iterable[T=>Boolean]) = {
      list.view.map( x => (x , preds.find( _(x) )) ).find( _._2.isDefined )
    }
    

    Alternatively, you could use a list of named predicates:

    def findP[T](list: Iterable[T],preds: Iterable[(T=>Boolean,String)]) = {
      list.view.map(x => (x , preds.find( _._1(x) ))).find( _._2.isDefined )
    }
    
    scala> findP(
         |   List(1,2,3,4,5,6),
         |   List( ((i:Int)=>i>4,"Fred") , ((i:Int)=>(i%6)==0,"Barney"))
         | )
    res2: Option[(Int, Option[((Int) => Boolean, String)])] =
      Some((5,Some((,Fred))))
    

    The result a little cluttered, but can be unwrapped easily enough to give exactly what you asked for:

    def findP[T](list: Iterable[T],preds: Iterable[(T=>Boolean,String)]) = {
      list.view.map(x => (x , preds.find( _._1(x) ))).find( _._2.isDefined ) match {
        case Some((i,Some((_,s)))) => Some((i,s))
        case _ => None
      }
    }
    

    (This is code for 2.8; switch "view" to "projection" for 2.7.)

提交回复
热议问题