Search code examples
listscalayield-keyword

Scala: Returning an element from a list that matches a condition


I have a list and I am trying to write a function returnMatchedElement(x:Int,y:Int,f:(Int,Int)=>Boolean) such that if a certain condition matches on an element of the list, it will return that element. Here's what I have got so far:

def returnMatchedElement(x:Int,l:List[Int],f:(Int,Int)=>Boolean):Int={
 for (y<-l if f(x,y)) yield y 
0}
def matchElements(a:Int,b:Int):Boolean= {if a==b true else false} 
val l1=List(1,2,3,4,5)

returnMatchedElement(3,l1,matchElements)
res13: Int = 0 

I am guessing I have a problem in understanding the yield keyword. What am I getting wrong here?

EDIT

The answer below works (thanks for that), but only if f returns boolean. I tried another example like this

def matchElements(a:Int,b:Int):Int= {if (a==b) 1 else 0} 
def returnMatchedElement(x:Int,l:List[Int],f:(Int,Int)=>Int):Option[Int]={l.find(y => f(x, y))}

And now the compiler says

<console>:8: error: type mismatch;
 found   : Int
 required: Boolean
       def returnMatchedElement(x:Int,l:List[Int],f:(Int,Int)=>Int):Option[Int]={l.find(y => f(x, y))}

Solution

  • Simply use find, it finds the first element of the sequence satisfying a predicate, if any:

    def returnMatchedElement(x: Int, l: List[Int], f: (Int,Int) => Boolean): Option[Int] = {
      l.find(y => f(x, y))
    }