Converting from Imperative to Functional Programming [Python to Standard ML]

I have a function specification that states that it should evaluate the polynomial function of a single variable. The coefficient of the function is set as a list. It also takes the value of the variable as real.

For example: eval (2, [4, 3, 2, 1]) = 26 (1 * x ^ 3 + 2 * x ^ 2 + 3 * x ^ 1 + 4 * x ^ 0, where x = 2)

Here's a function in python, but I'm not sure how to convert it to SML. I am having trouble finding a way to pass the iteration value without changing the function parameters. It should remain a real real list -> real function.

def eval(r, L):
    sum = 0
    for i in range(0, len(L)):
        sum = sum + L[i] * (r ** i)
    return sum
+3
source share
2

- . ( int int) r :

fun eval radix lst = let
  fun f (element, sum) = sum * radix + element
in
  foldr f 0 lst
end

:

- eval 10 [1,2,3];
val it = 321 : int
+4

, .

fun eval r =
    let fun step (power, sum) (coeff :: rest) =
                step (power * r, sum + coeff * power) rest
          | step (_, sum) nil = sum
    in step (1, 0)
    end

, , , .

fun eval r lst =
    let fun step (coeff, (power, sum)) = (power * r, sum + coeff * power)
        val (_, sum) = foldl step (1, 0) lst
    in sum
    end

Horner, KennyTM: sepp2k, , .

+1

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


All Articles