2012-03-15 53 views
2

我試圖做一個函數來解決標準ML中的單變量多項式方程,但它一直給我錯誤。多項式方程標準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 + 5×+ 1,和我們要通過2替代x,那麼我們就調用eval如下:

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

,其結果應該是23.0,但有時不同的輸入,它給了我不同的答案,但這個開關輸入它給我以下錯誤

smlnj/INIT/pervasive.sml:

未捕獲的異常空在提出209.19-209.24

什麼可以在這裏是我的問題嗎?

回答

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) 
+0

好吧,現在我看到我的錯誤是 非常感謝 – 2012-03-16 09:08:19

4

Empty是在空列表上運行hdtl時引發的。 hdtl幾乎從未在ML中使用;列表幾乎總是使用模式匹配來解構;它更漂亮和更安全。您似乎沒有空列表的情況,並且我沒有通過您的代碼來弄清楚您做了什麼,但您應該可以自己解決。