hak*_*ata 2 standards functional-programming eval sml
我正在尝试创建一个函数来解决标准 ML 中的单变量多项式方程,但它一直给我错误。
代码如下
(* Eval Function *)
- fun eval (x::xs, a:real):real =
let
val v = x (* The first element, since its not multiplied by anything *)
val count = 1 (* We start counting from the second element *)
in
v + elms(xs, a, count)
end;
(* Helper Function*)
- fun pow (base:real, 0) = 1.0
| pow (base:real, exp:int):real = base * pow(base, exp - 1);
(* A function that solves the equation except the last element in the equation, the constant *)
- fun elms (l:real list, a:real, count:int):real =
if (length l) = count then 0.0
else ((hd l) * pow(a, count)) + elms((tl l), a, count + 1);
Run Code Online (Sandbox Code Playgroud)
现在输入应该是多项式元素的系数和替换变量的数字,即如果我们有函数 3x^2 + 5x + 1,并且我们想用 2 替换 x,那么我们将调用 eval 如下:
eval ([1.0, 5.0, 3.0], 2.0);
Run Code Online (Sandbox Code Playgroud)
结果应该是 23.0,但有时在不同的输入上,它给了我不同的答案,但在这个输入上它给了我以下错误
未捕获的异常 Empty 在以下位置引发:smlnj/init/pervasive.sml:209.19-209.24
我的问题是什么?
Empty当您运行hd或tl在空列表上时引发。hd并且tl几乎从未在 ML 中使用过;列表几乎总是使用模式匹配来解构;它更漂亮,更安全。你似乎没有空列表的情况,我没有通过你的代码来弄清楚你做了什么,但你应该能够自己解决。
| 归档时间: |
|
| 查看次数: |
2610 次 |
| 最近记录: |