hakuna matata
hakuna matata

Reputation: 3327

polynomial equation standard ml

I'm trying to make a function that will solve a univariante polynomial equation in Standard ML, but it keeps giving me error.

The code is below

(* 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);

now the input should be the coefficient if the polynomial elements and a number to substitute the variable, ie if we have the function 3x^2 + 5x + 1, and we want to substitute x by 2, then we would call the eval as follows:

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

and the result should be 23.0, but sometimes on different input, its giving me different answers, but on this imput its giving me the following error

uncaught exception Empty raised at: smlnj/init/pervasive.sml:209.19-209.24

what could be my problem here?

Upvotes: 2

Views: 2784

Answers (2)

pad
pad

Reputation: 41290

After some recursive calls, elms function gets empty list as its argument. Since count is always greater than 0, (length l) = count is always false and the calls hd and tl on empty list are failed right after that.

A good way to fix it is using pattern matching to handle empty lists on both eval and elms:

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)

Upvotes: 4

newacct
newacct

Reputation: 122439

Empty is raised when you run hd or tl on an empty list. hd and tl are almost never used in ML; lists are almost always deconstructed using pattern matching instead; it's much prettier and safer. You don't seem to have a case for empty lists, and I didn't go through your code to figure out what you did, but you should be able to work it out yourself.

Upvotes: 5

Related Questions