While working through a problem found in 'Functional Programming in Scala':
Implement isSorted, which checks whether an Array[A] is sorted according to a given comparison function:
def isSorted[A](as: Array[A], ordered: (A,A) => Boolean): Boolean
While comparing my answer to the below solution provided by the author(s):
// Exercise 2: Implement a polymorphic function to check whether
// an `Array[A]` is sorted
def isSorted[A](as: Array[A], gt: (A,A) => Boolean): Boolean = {
@annotation.tailrec
def go(n: Int): Boolean =
if (n >= as.length-1) true
else if (gt(as(n), as(n+1))) false
else go(n+1)
go(0)
}
I am getting confused by the following line of code: else if (gt(as(n), as(n+1))) false
I thought when using a function as a parameter in Scala, one would need to actually define a separate function outside the scope of the current function (i.e. have another function defined that does what gt would need to do)? I don't see gt defined anywhere else, so how is it able to provide a Boolean value to use in isSorted?
Are my assumptions correct, or am I completely something missing here with using functions as parameters? A detailed explanation is much appreciated.
JavaScript questions and answers, JavaScript questions pdf, JavaScript question bank, JavaScript questions and answers pdf, mcq on JavaScript pdf, JavaScript questions and solutions, JavaScript mcq Test , Interview JavaScript questions, JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)