Search code examples
smlsmlnjpolynomial-math

Implementing a counter in SML


I am trying to solve a polynomial evaluation problem on SML, here is the current code I have:

fun eval (nil, b:real) = 0.0
|       eval(x::xs, a:real) = 
let val y:real = 0.0
fun inc z:real = z+1.0;
in
   (x*Math.pow(a,(inc y))) + eval(xs,a)
end;

The problem with this is that it only increments y once, is there a way to have y start at 0 and keep increasing by 1 with every recursion?


Solution

  • You can do that by using the concept of local function (or helper functions). Here's the code :

    local 
     fun helper(nil,b:real,_)=0.0
           |helper(x::xt,b:real,y)=(x*(Math.pow(b,(y)))) + helper(xt,b:real,y+1.0)
     in
     fun eval(x,a:real)= helper(x,a,0.0)
    end
    

    I Hope this can solve your problem :)