Error in recursive list logic

2019-09-20 03:50发布

问题:

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.

for example:

listMaker(3,f) = List(0,1,2)

so far I have created a helper class that takes 2 int and returns a list in that range.

the listMaker function is as follows:

def listMaker[A](length:Int, f:Int =>A):List[A] = length match{
  case 0 => List()
  case _ => listMaker(length,f)
}

my f function just takes a variable x and returns that:

 def f(x:Int)=x 

the comment below makes sense, but it still gets me errors. I think the edited code is an easier way to get where I would like to

However, now I get an infinite loop. What part of the logic am I missing?

回答1:

A recursive function typically has to gradually "bite off" pieces of the input data until there is nothing left - otherwise it can never terminate.

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)
}

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...).