Reputation: 33
I'm trying to write a recursive function that keeps going until a certain number is reached. The function has two parameters. The first is a list of strings, while the second is a number that tells me how many iterations I'm supposed to do. I've tried using let in the beginning, but I'm having a hard time figuring out how to increment the value I declare using let.
My function looks something like this.
somefunction l n = let m = 0 in
if (m < n) then somefunction (otherfunction l m) n
else l
This has the obvious problem that I don't increment the value of m anywhere so the function won't ever terminate. I'm still getting used to haskell so the syntax has been giving me some trouble. I feel like the solution to this should be pretty easy, but I can't seem to figure out how to go about it. I've thought of using a helper function that could increment the value of m and maybe call the otherfunction. This seems like the way to go, but I'm not sure on how to put it all together.
This is a homework assignment, so I would appreciate any kind of hint on how to solve this problem. I have all my other functions working, I just need to make them all work together.
Upvotes: 0
Views: 538
Reputation: 33
I ended up finding a solution after thinking about it for a while. I was thinking of using a helper function to keep track of the current iteration, but that was proving to be a bit difficult. In the end, I realized that I could simply call the recursive function in the opposite order so that the function would use the n and go all the way down to 0, then it would call otherfunction. This way, the result was printed in the correct order and I didn't have to use a helper function.
Upvotes: 0
Reputation: 48611
You do indeed need a helper function that calls itself with an updated argument each time.
somefunction l n = loop 0
where
loop m
| m < n = ...
| otherwise = ...
Upvotes: 2