Skip to content

Instantly share code, notes, and snippets.

@alkagin
Last active August 29, 2015 14:13
Show Gist options
  • Save alkagin/f75133e598421019b97c to your computer and use it in GitHub Desktop.
Save alkagin/f75133e598421019b97c to your computer and use it in GitHub Desktop.
Exercise 2.2 of Functional Programming In Scala
FILE "isSorted.scala"
def isSorted[A](as: Array[A], ordered: (A,A) => Boolean): Boolean = {
@annotation.tailrec
def go(n: Int): Boolean =
if (n >= as.length-1) true
else if (!ordered(as(n), as(n+1))) false
else go(n+1)
go(0)
}
def customOrder(n:Int, m:Int)= n <= m
SCALA REPL
scala> :load isSorted.scala
Loading isSorted.scala...
isSorted: [A](as: Array[A], ordered: (A, A) => Boolean)Boolean
customOrder: (n: Int, m: Int)Boolean
scala> isSorted(Array(1,1,2,3,2), customOrder)
res0: Boolean = false
scala> isSorted(Array(1,1,2,2,3), customOrder)
res1: Boolean = true
scala> isSorted(Array(3,2), customOrder)
res2: Boolean = false
scala> isSorted(Array(1,2), customOrder)
res3: Boolean = true
scala> isSorted(Range(1,20).toArray, customOrder)
res4: Boolean = true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment