[原创] 这么实现不是尾递归,该如何修改?
joachimz
2009-11-30
final def fb(x: BigInt):BigInt= {
if (0 == x) 1 else x*fb(x-1) } 我测试了一下,数据大了会发生StackOverflowError,还是递归操作,需要如何修改?谢谢 |
|
Eastsun
2009-11-30
scala> final def fac(n: BigInt): BigInt = { | def fac0(acc: BigInt,num: BigInt): BigInt = | if(num <= 0) acc else fac0(acc*num,num-1) | fac0(1,n) | } fac: (n: BigInt)BigInt |
|
night_stalker
2009-11-30
try this:
final def f(res: BigInt)(x: BigInt): BigInt = { if(x == 0) res else f(x * res)(x - 1) } val fac = f(1) _ |
|
nj0308
2009-11-30
scala有尾递归优化吗?我测试第二种在n为10000的时候照样overflow
|
|
joachimz
2009-11-30
night_stalker 写道 try this:
final def f(res: BigInt)(x: BigInt): BigInt = { if(x == 0) res else f(x * res)(x - 1) } val fac = f(1) _ 是可以的,我喜欢这个! 谢谢各位 |
|
幸存者
2009-11-30
scala支持尾递归优化?我怎么记得jvm不支持尾递归优化啊?
|
|
fineqtbull
2009-11-30
幸存者 写道 scala支持尾递归优化?我怎么记得jvm不支持尾递归优化啊?
Scala支持有限制的尾递归优化,这篇博客里有个详细的例子 http://fineqtbull.iteye.com/admin/blogs/499116 |