Given a higher order function that takes a function of type (A,A) => Boolean as a parameter:
def isSorted[A](as: Array[A], ordered : (A,A) => Boolean) : Boolean =
{
def doSorted(i: Int) : Boolean =
if (i >= as.length-1) true
else if (ordered(as(i), as(i+1))) false
else doSorted(i+1)
doSorted(0)
}
val lst1 = Array(1,2,3,4,5,6)
I can declare a function with known parameter types and pass it in:
def gtr(a : Int, b : Int) : Boolean = {
a > b
}
isSorted(lst1,gtr) /* works :-) */
I'd like to do one of the following. None of which seem to work for me:
Use a function with parametrised types:
def gtr[T](a : T, b : T) : Boolean = { a > b /* gives value > is not a member of type parameter T */ }
Is this possible in Scala. Do I have to tell the compiler that T is inherited from an object that has a > operator?
Use an anonymous function:
isSorted(lst1, ((x,y) => x > y)) /* gives missing parameter type */
Use Scala underscore magic to pass the > operator
isSorted(lst1, _>_) /* gives missing parameter type */
None of these three options work for me and I'm struggling to work out why. Can anyone tell me which of the above approaches are valid in Scala and what I'm doing wrong.