0

so I have to write a small program in SML ->>

a file named ‘p0.sml’ that contains a function named epoly, which accepts as parameters a list of real values a0 through an, and a single real value x. The list contains the coefficients of a polynomial of the form a0 + a1x + a2x 2 + … + anx n, where the real x used is the x parameter passed to your function. Your implementation must accept the list of coefficients as the first parameter and the value of x as the second. Your function must return the value of the polynomial specified by the parameters passed to it.

this is what I have so far but it won't compile because of a syntax error with as. "Error: syntax error found at AS". If you have any pointers that would be greatly appreciated.

fun epoly([], x:real) = 0.0
= epoly(L:real list as h::T, x:real) = h + (x * epoly(T, x));
Chris
  • 26,361
  • 5
  • 21
  • 42
Matalic17
  • 3
  • 1

1 Answers1

1

It looks like you have a typo. Your second = should be a |.

fun epoly([], x:real) = 0.0
  | epoly(L:real list as h::T, x:real) = 
      h + (x * epoly(T, x));

There is, further, no need to specify types. Your SML compiler can infer the types from data presented. Along with removing unnecessary bindings, this can be reduced to:

fun epoly([], _) = 0.0
  | epoly(h::T, x) = 
      h + (x * epoly(T, x));

From fun epoly([], _) = 0.0 we know epoly will take a tuple of a list and some type and return real.

From:

  | epoly(h::T, x) = 
      h + (x * epoly(T, x));

We know that x is being multiplied by a real, so x must be real. And since h is being added to a real, it must be a real, so the entire list is a real list.

Thus the type of epoly can be inferred correctly to be real list * real -> real.

Chris
  • 26,361
  • 5
  • 21
  • 42
  • 1
    Re: "no need to specify types": This is certainly true, but it might not be a bad idea for newcomers to Standard ML to put in a few type annotations reflecting their expectations so that they get useful error-messages when their expectations turn out to be, for whatever reason, wrong. – ruakh Jan 24 '22 at 00:09
  • That's fair. Though I think it's critical for newcomers to realize how type inference works. Otherwise they're missing one of the big draws of ML. – Chris Jan 24 '22 at 00:24