Horner's rule for polynomial evaluation: Difference between revisions

→‎{{header|Perl 6}}: adding recursive version
(→‎Recursive version: avoid relying on evaluation order for +)
(→‎{{header|Perl 6}}: adding recursive version)
Line 934:
 
say horner( [ -19, 7, -4, 6 ], 3 );</lang>
 
A recursive version would spare us the need for reversing the list of coeffcients (and thus possibly allowing progressive evaluation with lazy lists?). However, special care must be take in order to write it, because the way Perl 6 implements lists is not optimized for this kind of treatment. [[Lisp]]-styled lists are, and fortunately it is possible to emulate them with [http://doc.perl6.org/type/Pair Pairs] and the reduction meta-operator:
 
<lang perl6>multi horner(Numeric $c, $) { $c }
multi horner(Pair $c, $x) {
$c.key + $x * horner( $c.value, $x )
}
print horner( [=>](-19, 7, -4, 6 ), 3 );</lang>
 
=={{header|PHP}}==
1,934

edits