如何将函数调用的值存储到变量 [英] How to store value of function call to a variable
问题描述
我有此功能,需要检查数字 [1..n]
和 n
的 gdc
是否为 == 1
然后进行一些计算.所以我被困住了,因为我找不到将n的初始值存储到变量的方法.
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.
例如,如果我用数字7调用该函数是递归操作,则 n
变为 6
然后是 5
等,这样我就可以了"t gdc
正确;例如 1-7
然后 2-7
然后 3 -7
.您知道如何将 n
的值存储到 a
变量吗?
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)
推荐答案
使用辅助函数(通常称为 go
)进行递归,并在最外层调用中使用与在外部调用中不同的变量名.递归调用,如下所示:
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)
这篇关于如何将函数调用的值存储到变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!