[英]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? 最后一行和标记的行打印-1,为什么它们不起作用?
Because the condition in this line of your method findFirst
is wrong: 因为方法findFirst
这一行中的条件是错误的:
if (n <= as.length) -1
You probably meant: 您可能的意思是:
if (n >= as.length) -1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.