I'm having some difficulty trying to keep track of a counter variable in my function.
I created a function that takes a number as a single parameter and recursively multiplies the number by two, summing all the numbers multiplied by two together, the code below makes it more clear what I intend to do:
sum :: Float -> Float
sum x = x + sum (2*x)
However, the difficulty I am facing, is that I want the function to recurse only ten times. So I want it to stop once ten numbers have been added together. I tried using a counter to keep track of how many times the function has recursed, but to no avail.
This is what I tried:
sumTen :: Float -> Float
sumTen x n
where
n=10
|n == 0 = x
|otherwise = x + sumTen (2*x) (n-1)
I realize the code above does not work, counter n
would be given the value ten through every recursive call, meaning it will never reach the base case n == 0
.
What makes this so difficult is that sumTen
must be called using one parameter. In the code above, I tried to give the function a default parameter n
with a predetermined value, but it clearly does not work.
Can someone help me make the recursive function stop after 'n' recursive calls?
You can use an auxiliary function:
sumNRec x 0 = 0
sumNRec x times = x + sumNRec (x*2) (times - 1)
sumTen x = sumNRec x 10
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With