Compositing functions for Scala filter predicates

Image for post
Image for post
Photo by Chris Yang on Unsplash
scala> (1 to 50).filter(_ % 2 == 1)
res0: IndexedSeq[Int] = Vector(1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49)
  @scala.annotation.tailrec
def isPrime(number: Int): Boolean = number match {
case n if n < 0 => isPrime(-n)
case 0 => false
case 1 => false
case n => !((2 until n - 1) exists (n % _ == 0))
}
scala> (1 to 100).filter(isPrime(_))
res1: IndexedSeq[Int] = Vector(2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97)
scala> (1 to 100).filter(isPrime)
res2: IndexedSeq[Int] = Vector(2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97)
  def reverseDigits(n: Int): Int =
Integer.parseInt(n.toString.reverse)
scala> (1 to 100).filter(isPrime(reverseDigits))
^
error: missing argument list for method reverseDigits
Unapplied methods are only converted to functions when a function type is expected.
You can make this conversion explicit by writing `reverseDigits _` or `reverseDigits(_)` instead of `reverseDigits`.
scala> (1 to 100).filter(isPrime(reverseDigits _))
^
error: type mismatch;
found : Int => Int
required: Int
scala> (1 to 100).filter(isPrime(reverseDigits(_)))
^
error: type mismatch;
found : Int => Int
required: Int
scala> (1 to 100).filter(n: Int => isPrime(reverseDigits(n)))
^
error: ')' expected but '(' found.
^
error: ';' expected but ')' found.
((1 to 100): Range).filter(isPrime(reverseDigits(_))
((1 to 100): TraversableOnce[Int]).filter(isPrime(reverseDigits(_))
scala> def digitsReverseToPrime(n: Int): Boolean =
isPrime(reverseDigits(n))
digitsReverseToPrime: (n: Int)Boolean
scala> (1 to 100).filter(digitsReverseToPrime)
res6: IndexedSeq[Int] = Vector(2, 3, 5, 7, 11, 13, 14, 16, 17, 20, 30, 31, 32, 34, 35, 37, 38, 50, 70, 71, 73, 74, 76, 79, 91, 92, 95, 97, 98)
scala> (1 to 100).filter(n => isPrime(reverseDigits(n)))
res7: IndexedSeq[Int] = Vector(2, 3, 5, 7, 11, 13, 14, 16, 17, 20, 30, 31, 32, 34, 35, 37, 38, 50, 70, 71, 73, 74, 76, 79, 91, 92, 95, 97, 98)

is a composer and photographer from Detroit, Michigan. He has been working on a Java program to display certain mathematical diagrams.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store