-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPolymorphic.scala
56 lines (49 loc) · 1.24 KB
/
Polymorphic.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package FunctionalProgramming
/**
* Created by Karl Roth on 7/5/17.
*/
object Polymorphic {
/**
* @param as input array of any type
* @param ordered function for comparing
* elements of the array
* @return Boolean sorted or not
* @tparam A any type
*
* Checks to see if Array 'as' is sorted by the
* criterion of the function 'ordered'.
*/
def isSorted[A](as: Array[A], ordered: (A,A) => Boolean): Boolean = {
@annotation.tailrec
def loop(n: Int): Boolean = {
if (n+1 >= as.length) true
else if (ordered(as(n), as(n+1))) loop(n + 1)
else false
}
loop(0)
}
/**
* A function to check if a is less
* than b (i.e. ascending)
*/
def ascending(a: Int, b: Int): Boolean = {
if(a <= b) true
else false
}
/**
* A function to check if a is greater
* than b (i.e. descending)
*/
def descending(a: Int, b: Int): Boolean = {
if(a >= b) true
else false
}
/**
* An implementation of the above functions.
*/
def main(args:Array[String]): Unit = {
val as: Array[Int] = Array(1,1,3,4,5)
println("Ascending sort: " + isSorted[Int](as, ascending))
println("Descending sort: " + isSorted[Int](as, descending))
}
}