递归列表逻辑错误 [英] Error in recursive list logic
问题描述
我正在尝试在给定输入(长度和函数)的 Scala 中构建一个列表,输出将是一个从 0 到长度为 1 的列表.
I am trying to build a list in scala that given input (length,and a function) the output would be a list from 0 up to that length-1.
例如:
listMaker(3,f) = List(0,1,2)
到目前为止,我已经创建了一个辅助类,它接受 2 个 int
并返回该范围内的 list
.
so far I have created a helper class that takes 2 int
and returns a list
in that range.
listMaker
函数如下:
def listMaker[A](length:Int, f:Int =>A):List[A] = length match{
case 0 => List()
case _ => listMaker(length,f)
}
我的 f
函数只需要一个变量 x 并返回:
my f
function just takes a variable x and returns that:
def f(x:Int)=x
下面的评论是有道理的,但它仍然让我出错.我认为编辑后的代码更容易到达我想要的地方
但是,现在我得到了一个无限循环.我遗漏了哪一部分逻辑?
However, now I get an infinite loop. What part of the logic am I missing?
推荐答案
递归函数通常必须逐渐咬掉"输入数据的片段,直到没有任何剩余 - 否则它永远不会终止.
A recursive function typically has to gradually "bite off" pieces of the input data until there is nothing left - otherwise it can never terminate.
在您的特定情况下,这意味着 length
必须在每次递归调用时减少,直到达到零.
What this means in your particular case is that length
must decrease on each recursive call until it reaches zero.
def listMaker[A](length:Int, f:Int =>A):List[A] = length match{
case 0 => List()
case _ => listMaker(length,f)
}
但是您并没有减少 length
- 您将它原封不动地传递给下一个递归调用,因此,您的函数无法终止.
But you are not reducing length
- you are passing it unchanged to the next recursive call, so, your function cannot terminate.
(还有其他问题——你需要在递归时建立你的结果列表,但你当前的代码只是返回一个空列表.我认为这是一个学习练习,所以我没有提供工作代码...).
(There are other problems too - you need to build up your result list as you recurse, but your current code simply returns an empty list. I assume this is a learning exercise, so I'm not supplying working code...).
这篇关于递归列表逻辑错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!