Take a detailed look at implementation of isSorted function, what would be the result of applying the following anonymous function with array to it?

def isSorted[A](as: Array[A], ordering: (A, A) => Boolean): Boolean = {
 @annotation.tailrec
 def go(n: Int): Boolean =
   if (n >= as.length - 1) true
   else if (ordering(as(n), as(n + 1))) false
   else go(n + 1)

 go(0)
}

isSorted(Array(7, 5, 1, 3), (x: Int, y: Int) => x < y)
Explanation
Let’s look how the function is executed step-by-step:
n == 0
ordering(as(0), as(1)) == ordering(7, 5) == (7 < 5) == false

n == 1
ordering(as(1), as(2)) == ordering(5, 1) == (5 < 1) == false

n == 2
ordering(as(2), as(3)) == ordering(1, 3) == (1 < 3) == true
Since "ordering" call returned "true", the result of if-condition inside "go" and overall result is false.

Source: Scala Exercises: getting started with functional programming
Theory
  • Higher-order Functions
    Scala allows the definition of higher-order functions. These are functions that take other functions as parameters, or whose result is a function. Here is a function apply which takes another function f and a value v and applies function f to v:
    def apply(f: Int => String, v: Int) = f(v)
    Note: methods are automatically coerced to functions if the context requires this.
    Read more: Scala documentation

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback