max12424
max12424

Reputation: 13

How to store value of function call to a variable

I have this function where I need to check if the gdc of the numbers [1..n] and n is == 1 and do some calculations then. So I am stuck because I can't find a way to store the initial value of n to a variable.

For example, if I call the function with the number 7 its a recursion so n becomes 6 then 5 etc so I can't gdc properly; for example 1-7 then 2 - 7 then 3 -7. Do you know how I can store the value of n to a variable ?

myproduct :: Integer->Integer

myproduct 0 = 1
myproduct n  
  |gcd n (n from first call)  /= 1 = myproduct (n-1) 
  |otherwise = x
  where 
    x = n * myproduct (n - 1)

Upvotes: 1

Views: 206

Answers (1)

Use a helper function (often called go) to do the recursion, and use a different variable name in the outermost call than in the recursive call, like this:

myproduct :: Integer->Integer

myproduct orig_n = go orig_n
  where
    go 0 = 1
    go n
      |gcd n orig_n  /= 1 = go (n-1)
      |otherwise = x
      where
        x = n * go (n - 1)

Upvotes: 6

Related Questions