簡體   English   中英

Scala,我的通用函數“ findFirst”不起作用

[英]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))  

最后一行和標記的行打印-1,為什么它們不起作用?

因為方法findFirst這一行中的條件是錯誤的:

if (n <= as.length) -1

您可能的意思是:

if (n >= as.length) -1

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM