Horner's algorithm in SML?

I am trying to implement the Horner algorithm in SML.

fun horner(lst1:real list,x:real) = 
  let
    val i = ref 1
    val result = ref (List.last(lst1))
    in
      if (lst1) = ([]:real list) then 0.0 
      else
        while (!i <= length(lst1)-1) do
          (result:=!result*x+List.nth(lst1,length(lst1)-(!i)-1);
          i := !i+1);
          !result
      end;

Takes {n}, coeff of x ^ n, as its original result, then using horner evaluates the polynomial.

Estimated as ((a {n} * x + a {n-1}) * x + a {n-2}) .. The list contains polynomial coefficients. The problem is that the part is "if lst1 = [] .... else". Using only the while loop makes the program workable. But I can’t think of anything that’s wrong with this part.

-5
source share
1 answer

- , , , . SML, Java, , .

, , . , . if-then-else, , . :

fun horner ([]   , x) = 0.0
  | horner (n::ns, x) = ...

. -, - n , ns - . -, .

. horner , result , . , , ref . .

fun horner ([]   , x, acc) = acc
  | horner (n::ns, x, acc) = ...

, , , :

fun horner' ([]   , x, acc) = acc
  | horner' (n::ns, x, acc) = ...

fun horner (xs, x) = horner' (xs, x, 0.0)

, , SML , . , let:

fun horner (xs, x) = let
                       fun horner' ([]   , x, acc) = acc
                         | horner' (n::ns, x, acc) = ...
                     in
                       horner' (xs, x, 0.0)
                     end

, horner'.

fun horner (xs, x) = let
                       fun horner' ([]   , x, acc) = acc
                         | horner' (n::ns, x, acc) = horner' (ns, x, n + x * acc)
                     in
                       horner' (xs, x, 0.0)
                     end

, horner:

horner ([3.0, 2.0, 4.0], 2.0) ~> horner' ([3.0, 2.0, 4.0], 2.0, 0.0)
                              ~> horner' ([2.0, 4.0]     , 2.0, 3.0 + 2.0 * 0.0)
                              ~> horner' ([2.0, 4.0]     , 2.0, 3.0)
                              ~> horner' ([4.0]          , 2.0, 2.0 + 2.0 * 3.0)
                              ~> horner' ([4.0]          , 2.0, 8.0)
                              ~> horner' ([]             , 2.0, 4.0 + 2.0 * 8.0)
                              ~> horner' ([]             , 2.0, 20.0)
                              ~> 20.0
+3

Source: https://habr.com/ru/post/1668785/


All Articles