Scala定义f:
def f[X](xs:List[X]):List[X]={
xs match{
case Nil=>xs
case y::ys=>y::f(ys)
}
}
考虑表达式:
f(List(1,2))
我很好奇为什么答案不是List(1,2,1,2)或List(1,2,List(1,2))
因为,
Step1.(when we input the List(1,2))
it will match the "case y::ys=>y::f(ys)"
So it becomes "case 1::2=>1::f(2)"
Continue to recursive.
Step2,
it also match the "case y::ys=>y::f(ys)"
So it becomes "case 2::Nil=>2::f(Nil)"
Continue to recursive.
Step3,
it will match "case Nil=>xs"
So it becomes "case Nil=>List(1,2)"
And because previous steps 1 and 2 are recursive.
when we meet the base case it should become
"1::2::List(1,2)"
但它看起来只是直接返回xs(List(1,2))作为最终答案。 我是否对scala递归函数有误解?
答案 0 :(得分:1)
您在第3步中犯了一个错误。
在步骤3之前,您的通话是
f(xs=Nil)
因此它与Nil相匹配,并且由于xs也为nil,它将返回它。意味着它实际上变成了
case Nil => Nil
递归不保留原始参数。
它变成
> 1 :: 2 :: Nil
> 1 :: List(2)
> List(1,2)