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

I'd do this: Scala 2.8: def find2pT(l: ListT, 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 find2pT(l: ListT, 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.

Generalised to a list of predicates def findPredsOrT(l: ListT, ps: ListT => Boolean): Option(T, ListBoolean) = l.view. Map(el => (el, ps. Map(_.

Apply(el)))). Find(t => t. _2.

Contains(true)) – retronym Feb 1 '10 at 10:52 Great solution. Thank you for let me discover view/projection, it seems very useful! – Filippo Tabusso Feb 1 '10 at 11:20.

Def findT(l1 : ListT, c1 : T => Boolean, c2 : T => Boolean) = ((None : Option(String, T)) /: l1)( (l, n) => l match { case x : Some_ => l case x if c1(n) => Some("c1", n) case x if c2(n) => Some("c2", n) case _ => None }) scala> find(l1, c1, c2) res2: Option(String, java.lang. String) = Some((c1,B)) scala> find(l2, c1, c2) res3: Option(String, java.lang. String) = Some((c2,AA)) Depending on your requirements you could have a parameter MapT => Boolean, String for the label strings to return: def findT(l1 : ListT, fs : MapT => Boolean, String) or define your own operators.

This will evaluate the whole list where find aborts for the first element found.

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 findPT(list: IterableT, preds: IterableT=>Boolean) = { list.view. Map( x => (x , preds.

Find( _(x) )) ). Find( _. _2.

IsDefined ) } Alternatively, you could use a list of named predicates: def findPT(list: IterableT,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 findPT(list: IterableT,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. ).

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions