How to store value of function call to a variable

久未见 提交于 2021-02-05 06:43:45

问题


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)

回答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)


来源:https://stackoverflow.com/questions/55133331/how-to-store-value-of-function-call-to-a-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!