从命令式编程到函数式编程的转换 [Python 到标准 ML]
我有一个函数规范,指出它应该评估一个变量的多项式函数。函数的系数以列表形式给出。它还接受变量的实数值。
例如: eval(2, [4, 3, 2, 1]) = 26 (1*x^3 + 2*x^2 + 3*x^1 + 4*x^0, 其中 x = 2)
这是python 中的函数,但我不知道如何将其转换为 SML。我无法找到一种在不更改函数参数的情况下向其传递迭代值的方法。它需要保持一个真实的*真实的列表->实函数。
def eval(r, L):
sum = 0
for i in range(0, len(L)):
sum = sum + L[i] * (r ** i)
return sum
I have a function specification that states it that should evaluate a polynomial function of one variable. The coefficient of the function is given as a list. It also accepts the value of the variable as a real.
For example: eval(2, [4, 3, 2, 1]) = 26 (1*x^3 + 2*x^2 + 3*x^1 + 4*x^0, where x = 2)
Here's the function in python, but I'm not sure how to convert it to SML. I'm having trouble finding a way to pass it the iteration value without changing the parameters of the function. It needs to remain a real * real list -> real function.
def eval(r, L):
sum = 0
for i in range(0, len(L)):
sum = sum + L[i] * (r ** i)
return sum
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在函数语言中表达和的常用方法是折叠。您可以通过在每次迭代中将总和与 r 相乘来消除对索引(以及将一个 int 提升为另一个 int 次幂的函数)的需要:
现在可以像这样使用该函数:
The usual way to express sums in functional languages is a fold. You can get rid of the need for an index (and a function to raise an int to the power of another int) by multiplying the sum with r in each iteration:
Now the function can be used like this:
您可以使用显式递归来遍历系数列表、对基数求幂并对总数求和。
从结构上来说,这和折叠一模一样,如果我们把它换成折叠就更清楚了。
您可以反转操作顺序以使用 Horner 的方案,如 KennyTM 的评论中所述:这将导致 sepp2k 的答案,它需要一半的乘法,但使用更多的堆栈空间。
You can use explicit recursion to walk through the list of coefficients, exponentiate the radix, and sum up the total.
Structurally, this is exactly like a fold, and it becomes clearer if we replace it with one.
You can reverse the order of operations to use Horner's scheme, as mentioned in KennyTM's comment: that would result in sepp2k's answer, which requires half as many multiplications, but uses more stack space.