Reputation: 41
Can you please help me with this:
I have 2 functions:
f1: Int => Boolean
f2: Int => Boolean
now I want to combine/merge these functions with logical OR, something like:
f3: Int => f1 || f2
so function f3 will return true only if one of functions f1 and f2 returns true
how to write such function?
thanks a lot
Upvotes: 4
Views: 2610
Reputation: 3367
That would be:
def union(f: Int => Boolean, g: Int => Boolean): Int => Boolean= { x => f(x) || g(x)}
The question here is from where comes 'x', isn't it? Well... it would be the same question as if you ask where f or g come from. You don't even think about that, those are parameters and that suffices. Same answer applies. Forget about the rest of the function. Does x => f(x) || g(x)
make sense? As long as f and g return boolean it does, doesn't it? So there you are.
I would say that if you read the whole function from inside out, it has obvious meaning.
Cheers!
Upvotes: 3
Reputation: 106
examples of composing predicates: http://danielwestheide.com/blog/2013/01/23/the-neophytes-guide-to-scala-part-10-staying-dry-with-higher-order-functions.html
Upvotes: 0
Reputation: 20515
So this is a good bit of infrastructure, but I've found it useful in the past to actually add boolean operations as effectively native operations on predicates. It's one of the things I keep in my grab-bag of utility functionality, and eventually import into pretty much every project I write.
object PredicateUtils {
implicit class RichPredicate[A](f: Function1[A, Boolean]) extends Function1[A, Boolean] {
def apply(v: A) = f(v)
def &&(g: Function1[A, Boolean]): Function1[A, Boolean] = {
(x: A) => f(x) && g(x)
}
def ||(g: Function1[A, Boolean]): Function1[A, Boolean] = {
(x: A) => f(x) || g(x)
}
def unary_! : Function1[A, Boolean] = {
(x: A) => !f(x)
}
}
}
Once you've done that, then all you have to do is
import PredicateUtils
val f3 = f1 || f2
val f4 = !f1 && f2
Upvotes: 6
Reputation: 8128
def fun_or[T](f1: T => Boolean, f2: T => Boolean)(x: T) = f1(x) || f2(x)
then:
val f3 = fun_or(f1, f2)
Upvotes: 2