I'm new to Scala and I'm trying to figure out what predicates are and the correct way to used them. The information I found online is not very clear to me or it assumes previous knowledge of predicates. Can someone explain what they are and perhaps show a few examples of how to use them in Scala?
A predicate is a function that returns a Boolean . For example, to check if an Integer is even we can define the function isEven . scala> def isEven(i: Int) = i % 2 == 0 isEven: (i: Int)Boolean.
A predicate is a function that returns a Boolean
.
For example, to check if an Integer is even we can define the function isEven
.
scala> def isEven(i: Int) = i % 2 == 0
isEven: (i: Int)Boolean
It behaves as you would expect.
scala> isEven(2)
res1: Boolean = true
So, you can then pass this into a function like filter
that takes a function that returns a boolean. The type signature for this is p: (A) ⇒ Boolean)
where p
is short for predicate.
scala> List(1,2,3,4,5,6,7,8,9,10).filter(isEven)
res2: List[Int] = List(2, 4, 6, 8, 10)
See Scala School for some good reading.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With