Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...