Skip to content

Instantly share code, notes, and snippets.

@manjuraj
Last active January 2, 2016 23:49
Show Gist options
  • Save manjuraj/8378326 to your computer and use it in GitHub Desktop.
Save manjuraj/8378326 to your computer and use it in GitHub Desktop.
Using higher order functions to achieve abstraction and conciness
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