Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
169 views
in Technique[技术] by (71.8m points)

scala - Error in recursive list logic

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...