Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell- How to keep track of counter in recursive function

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?

like image 550
buydadip Avatar asked Dec 12 '22 01:12

buydadip


1 Answers

You can use an auxiliary function:

sumNRec x 0     = 0 
sumNRec x times = x + sumNRec (x*2) (times - 1)

sumTen x = sumNRec x 10
like image 174
Fernando Avatar answered Mar 17 '23 17:03

Fernando