How to write a function that calculates F(x) if x = integer in sml

Viewed 39

I am trying to write a recursive function that takes a list and an integer as a parameter, where the list is the polynomial i.e. (val P = [5.0, 4.0, 0.0, 1.0] = x^3 + 4x - 5) and the integer parameter is x i.e. x = 2 so f(2) = x^3 +4x - 5. Here is what Ive come up so far...

val P = [5.0, 4.0, 0.0, 1.0]; val a = 2;

fun eval(nil, a) = 0.0
    | eval(x::xs, a:real) = 
        x + (eval(xs, a) * a)
eval(P, a);

after running the code it is giving me this error: stdIn:22.4-24.11 Error: operator is not a function [tycon mismatch] operator: real in expression: (eval (xs,a) * a) eval

the way the recursion is "suppose" to work is P = a + Qx where P is the original list and a is x in x::xs and Q is xs and the x is the integer parameter that was passed. Any help would be much appreciated. Thanks!!

2 Answers

Ok so I figured it out. Here go...

val P = [~5.0, 4.0, 0.0, 1.0];
val a = 2.0;

fun eval(nil, a) = 0.0
  | eval(x::xs, a:real) = 
    x + (eval(xs, a) * a);

eval(P, a);

Since you answered your own question (good on you!) here's another way to write it:

fun eval ([], _) = 0.0
  | eval (x::xs, y) = x + eval (xs, y) * y
Related