如何修复Scala泛型函数?

时间:2019-01-03 15:19:35

标签: scala generics functional-programming

我正在尝试从一本书中进行练习(Manning-“ Scala中的功能编程”)。要求编写一个泛型函数来测试给定数组是否根据自定义比较谓词排序。虽然Strings函数可以按预期工作,但Generic可以编译,但是尝试使用:isSorted(Array("A", "B") lessThan)失败,并产生错误消息:

No implicit view available from T => Ordered[T]

功能:

def isSorted[A](xs: Array[A], compare: (A, A) => Boolean) (implicit f: A => Ordered[A]): Boolean = {

    def helper[T](ys: Array[T], g: (T, T) => Boolean)(implicit f: T => Ordered[T]): Boolean = {
        if (ys.length == 2) g(ys(0), ys(1))
        else {
            if (! g(ys(0), ys(1))) false
            else
                helper(ys.tail, g)
        }
    }

    if (xs.length == 1) return true
    else{
        helper(xs, compare)
    }
}

def isSortedStr (xs: Array[String], compare: (String, String) => Boolean): Boolean = {

    def helper(ys: Array[String], g: (String, String) => Boolean): Boolean = {
        if (ys.length == 2) g(ys(0), ys(1))
        else {
            if (! g(ys(0), ys(1))) return false
            else
                helper(ys.tail, g)
        }
    }

    if (xs.length == 1) return  true
    else{
        return helper(xs, compare)
    }
}

}

比较功能:

def greaterThan[T](x : T, y : T)(implicit f : T => Ordered[T]) = x > y
def lessThan[T]   (x : T, y : T)(implicit f : T => Ordered[T]) = x < y

有什么想法吗?谢谢。

1 个答案:

答案 0 :(得分:0)

已解决,问题出在所提供的比较功能上,@ Andrey Tyukin确实是位,

val sortGe = (a: String, b: String) => a >= b
def isSorted[A](xs: Array[A], compare: (A, A) => Boolean): Boolean = {

    def helper[T](ys: Array[T], g: (T, T) => Boolean): Boolean = {
        if (ys.length == 2) g(ys(0), ys(1))
        else {
            if (! g(ys(0), ys(1))) false
            else
                helper(ys.tail, g)
        }
    }

    if (xs.length == 1) return true
    else{
        helper(xs, compare)
    }
}