多项式方程标准ml

时间:2012-03-15 19:59:28

标签: functional-programming standards 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);

现在输入应该是系数,如果多项式元素和数字替换变量,即如果我们有函数3x ^ 2 + 5x + 1,并且我们想用x替换2,那么我们将调用评估如下:

eval ([1.0, 5.0, 3.0], 2.0);

,结果应该是23.0,但有时在不同的输入上,它给了我不同的答案,但在这个输入上它给我以下错误

  

未捕获的异常空出现在:   smlnj / INIT / pervasive.sml:209.19-209.24

这可能是我的问题?

2 个答案:

答案 0 :(得分:4)

在空列表中运行Emptyhd时会引发

tlhdtl几乎从不用于ML;列表几乎总是使用模式匹配来解构;它更漂亮,更安全。您似乎没有空列表的情况,我没有通过您的代码来弄清楚您做了什么,但您应该能够自己解决。

答案 1 :(得分:4)

在一些递归调用之后,elms函数将空列表作为其参数。由于count始终大于0,(length l) = count始终为false,并且空列表上的调用hdtl在此之后就会失败。

解决问题的一个好方法是使用模式匹配来处理evalelms上的空列表:

fun elms ([], _, _) = 0.0
  | elms (x::xs, a, count) = (x * pow(a, count)) + elms(xs, a, count + 1)

fun eval ([], _) = 0.0 
  | eval (x::xs, a) = x + elms(xs, a, 1)
相关问题