Reputation: 163
I am relatively new to Scala functional programming. I have been following a few tasks, however, finding difficult to understand or implement the concept below.
Basically, I want write a function which takes a list and a function, and returns true if the function returns true for at least one item in the list. An example would be: hasMatch(isEven,List(1,2,3,5)) will return true, but hasMatch(isEven,List(1,3,5)) will return false.
A sample solution or hint is provided with the problem, as seen below:
def hasMatch (fn:(Int)=>Boolean,lst:List[Int]):Boolean = {
lst.foreach ((x:Int) => if (fn(x)) return true)
return false
}
Could someone please explain the concept behind it or ways to implement it.
Upvotes: 1
Views: 1339
Reputation: 15345
Your isEven function is going to determine the outcome of the hasMatch function. So assuming that your isEven function is defined like this:
def isEven(x: Int): Boolean = x % 2 == 0
You can now define your hasMatch function like this:
def hasMatch(fn: Int => Boolean, l: List[Int]): Boolean = {
l.exists(elem => fn(elem))
}
You then call the function like this:
hasMatch(isEven, List(1,2,3,5))
Upvotes: 1
Reputation: 40500
The biggest problem with your implementation: return
is a really bad thing in scala, and should (almost) never be used.
Also, there are more idiomatic ways to do what you want, rather than spelling out the imperative loop with foreach
.
Here is one possibility:
def hasMatch[T](lst: List[T])(fn: T => Boolean) = lst.exists(fn)
I added a type parameter to your definition, so that it works for any type, not just Int
. Also, I made fn
the last argument, and moved it into a separate list. It makes it easier to pass anonymous functions in:
if (hasMatch(List(1,2,3,4,5)) { _ > 5 }) println("There are elements greater than five")
Upvotes: 1
Reputation: 7553
def hasMatch(fn: Int => Boolean, lst: List[Int]): Boolean = lst.exists(fn)
The exists
function has the same semantics as what you're after - it returns true if fn returns true for at least one element, false otherwise.
Upvotes: 1