Reputation: 41909
Given these two functions:
scala> def maybe(x: Int): Boolean = x % 2 == 0
maybe: (x: Int)Boolean
scala> def good(x: Int): Boolean = x == 10
good: (x: Int)Boolean
Can I apply both good
and maybe
functions together?
scala> List(10) filter good filter maybe
res104: List[Int] = List(10)
scala> List(10) filter (good && maybe)
<console>:17: error: missing arguments for method good;
follow this method with `_' if you want to treat it as a partially applied function
List(10) filter (good && maybe)
^
Upvotes: 1
Views: 2654
Reputation: 39577
scala> def maybe(x: Int): Boolean = x % 2 == 0
maybe: (x: Int)Boolean
scala> def good(x: Int): Boolean = x % 3 == 0
good: (x: Int)Boolean
scala> (1 to 20) filter { i => List(good _, maybe _).forall(_(i)) }
res1: scala.collection.immutable.IndexedSeq[Int] = Vector(6, 12, 18)
Upvotes: 3
Reputation: 549
You could evaluate them inside an anonymous function:
List(10) filter { x => good(x) && maybe(x) }
You can't really use andThen
because composition is like the transitive property.
[(A => Boolean) && (A => Boolean)] != [(A => B) => C]
// ^ What you want ^ Composition
Upvotes: 4