Scala,我的通用功能“findFirst”不起作用

时间:2015-10-25 17:09:17

标签: java scala templates generics functional-programming

object FPSEx2_1 {

    def factorial(n: Int) : Int = {
        def go(n: Int, acc: Int) : Int = {
            if (n <= 0) acc
            else go(n-1, n*acc)
        }
        go(n, 1)
    }
    def fib(n: Int) : Int = {
        @annotation.tailrec
        def go(n:Int, prev: Int, cur: Int): Int = {
            if( n == 0) prev
            else go(n-1, cur, prev + cur)
        }
        go(n, 0,1)
    }
    def formatResult(name: String, n: Int, f:Int => Int) = {
        val msg = "The %s of %d is %d."
        msg.format(name, n, f(n))
    }

    def findFirst[A] (as: Array[A], p: A => Boolean): Int = {
        @annotation.tailrec
        def loop(n: Int) : Int = 
            if (n <= as.length) -1
            else if (p(as(n))) n
            else loop(n + 1)
        loop(0)
    }

    def isPear(p : String) : Boolean = {
        if (p == "pears") true
        else false
    }

    def main(args: Array[String]) : Unit = {
        println("hello word")
        println(factorial(3))
        println(fib(4))
        println(formatResult("factorial", 4, factorial))

        var fruit = Array("apples", "oranges", "pears")

        println(findFirst(fruit, isPear))  // this line prints -1, why doesn 't it work?
    }
}

println (findFirst (fruit, isPear))  

最后一行和标记的行打印-1,为什么他们不工作?

1 个答案:

答案 0 :(得分:3)

因为方法findFirst的这一行中的条件错误:

if (n <= as.length) -1

你可能意味着:

if (n >= as.length) -1