Scala递归闭包编译错误
我正在尝试实现一个记忆斐波那契数函数,但遇到了无法解决的编译错误。以下代码是我到目前为止所拥有的。
var fibs = Map.empty[Int, Int]
fibs += 0 -> 1
fibs += 1 -> 1
fibs += 2 -> 2
val fib = (n: Int) => {
if (fibs.contains(n)) return fibs.apply(n)
else{
// Error here
val result = fib(n - 1) + fib(n - 2)
fibs+= n -> result
return result
}
}
println(fib(100))
错误是:
递归
fib
需要类型
我尝试在不同的地方输入闭包的返回类型,但我似乎无法让它工作。
声明闭包如 val fib = (n: Int): Int =>; {
产生不同的编译错误。
你能帮我解决这个编译错误吗?
I am trying to implement a memoized Fibonacci number function, and I am running into a compile error that I can't sort out. The following code is what I have so far.
var fibs = Map.empty[Int, Int]
fibs += 0 -> 1
fibs += 1 -> 1
fibs += 2 -> 2
val fib = (n: Int) => {
if (fibs.contains(n)) return fibs.apply(n)
else{
// Error here
val result = fib(n - 1) + fib(n - 2)
fibs+= n -> result
return result
}
}
println(fib(100))
The error is:
Recursive
fib
needs type
I have tried entering a return type for the closure in various places, but I can't seem to get it to work.
Declaring the closure like val fib = (n: Int): Int => {
yields a different compile error.
Could you please help me fix this compile error?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以按照 Ben Jackson 的建议定义一个方法(即
def fib (n: Int): Int = ...
)。函数值不能递归。编辑:事实证明 它们可以是递归的;您只需要为类型推断器提供更多帮助即可。另外,您需要摆脱return
;它只能在方法中使用。以下内容有效:
您还应该看看这篇博文来了解如何您可以借助 lambda 抽象出记忆逻辑。
You can define a method as suggested by Ben Jackson (i.e.
def fib (n: Int): Int = ...
).Function values cannot be recursive.EDIT: It turns out they can be recursive; you just need to help the type inferencer a bit more. Also, you need to get rid ofreturn
; it can only be used in the methods.The following works:
Also you should take a look at this blogpost to understand how you can abstract away the memoization logic with help of lambdas.
您必须显式设置递归函数的返回类型。它无法推断类型,因为推断将是循环的。所以:def fib (n: Int): Int = ...
You have to explicitly set the return type of recursive functions. It can't infer the type because the inference would be cyclic. So:
def fib (n: Int): Int = ...
去掉
return
,因为它们只能与def
一起使用,不能与val
一起使用,并声明fib
' s 类型,因为这是 Scala 对递归定义的要求。请注意,
fib(100)
会溢出Int
Get rid of the
return
, as they can only be used withdef
, notval
, and declarefib
's type, as that's a Scala requirement for recursive definitions.Note that
fib(100)
will overflow anInt