Last active
January 2, 2016 23:49
-
-
Save manjuraj/8378326 to your computer and use it in GitHub Desktop.
Using higher order functions to achieve abstraction and conciness
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type Pred[A] = A => Boolean | |
def not[A](p: Pred[A]): Pred[A] = a => !p(a) | |
def and[A](p1: Pred[A], p2: Pred[A]): Pred[A] = a => p1(a) && p2(a) | |
def or[A](p1: Pred[A], p2: Pred[A]): Pred[A] = a => p1(a) || p2(a) | |
def isDivisibleBy(k: Int): Pred[Int] = i => i % k == 0 | |
def isEven: Pred[Int] = isDivisibleBy(2) | |
def isOdd: Pred[Int] = not(isEven) | |
// notice that and() and or() can be abstracted further, as follows | |
def lift[A](f: (Boolean, Boolean) => Boolean): (Pred[A], Pred[A]) => Pred[A] = | |
(p1, p2) => a => f(p1(a), p2(a)) | |
def or[A]: (Pred[A], Pred[A]) => Pred[A] = lift[A](_ || _) | |
def and[A]: (Pred[A], Pred[A]) => Pred[A] = lift[A](_ && _) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment