Horner's rule for polynomial evaluation

Functional:

func horner(coeff, x) {
    coeff.reverse.reduce { |a,b| a*x + b }
}
 
say horner([-19, 7, -4, 6], 3)   # => 128

Recursive:

func horner(coeff, x) {
    (coeff.len > 0) \
        ? (coeff[0] + x*horner(coeff.last(-1), x))
        : 0
}

say horner([-19, 7, -4, 6], 3)   # => 128

Last updated