Scala阶乘函数返回结果存疑:调用fact(4)得24而非预期12
Hey Tyler, let's walk through exactly why fact(4) returns 24 instead of the 12 you expected—your recursive function is working correctly, you just missed a step in the recursive breakdown!
First, let's recap your function definition (which is perfectly valid for calculating factorials):
def fact(n:Int):Int = if (n<2) 1 else n*fact(n-1)
Let's expand the recursive calls step by step for fact(4):
- When you call
fact(4), since 4 is not less than 2, it evaluates to4 * fact(3) - Next,
fact(3)evaluates to3 * fact(2)(3 is also not <2) - Then
fact(2)evaluates to2 * fact(1)(2 is not <2) - Finally,
fact(1)hits the base case: since 1 < 2, it returns1
Now let's compute the results working backwards:
fact(2) = 2 * 1 = 2fact(3) = 3 * 2 = 6fact(4) = 4 * 6 = 24
Your confusion came from assuming fact(3) equals 3, but remember—fact(3) doesn't just return 3, it returns 3 multiplied by the result of fact(2), which itself is 2 multiplied by fact(1). That's the magic (and sometimes tricky part) of recursion: each call depends on the next smaller call until we hit the base case.
If you want to verify this further, try printing intermediate values by modifying your function slightly:
def fact(n:Int):Int = { println(s"Calculating fact($n)") if (n<2) 1 else n*fact(n-1) }
Running fact(4) will show you each step of the recursion, making it even clearer how the values build up to 24.
内容的提问来源于stack exchange,提问作者Tyler

