I've this method:
def isSorted[A](as: Array[A], ordered: (A, A) => Boolean): Boolean = {
val sorted = for (it <- as.sliding(2))
yield {
if (it.length == 2) ordered.apply(it(0), it(1))
else true
}
sorted.find(!_).isEmpty
}
What I'd like to do is use foldLeft
and apply the binary operator. However, foldLeft
requires an initial value and I don't know what initial value I can provide without knowing the real type of A
.
For initial value for foldLeft you could use head of your input array. However foldLeft is not a good choise to check if array is sorted, since you should terminate method when first unsorted element found but foldLeft will traverse whole array
Edit:
I would use the combination of zip with tail and exists:
Adding to the other answers, you probably do not want to iterate through the entire array, but rather terminate the moment you find an unordered pair. So, how about this?
I think what you're doing can be simplified.
Or, perhaps a little more concisely (but not necessarily easier to understand):
UPDATE
OK, I think I've got the concise prize nailed.