简体   繁体   中英

Scala, my generic function “findFirst” doesn 't work

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))  

The last and the marked line print -1, why don 't they work?

Because the condition in this line of your method findFirst is wrong:

if (n <= as.length) -1

You probably meant:

if (n >= as.length) -1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM