Horner's rule for polynomial evaluation: Difference between revisions

→‎{{header|Perl 6}}: showing a version with potentially infinite list of coefficients
(→‎{{header|Perl 6}}: restoring alternate solution using composition operator)
(→‎{{header|Perl 6}}: showing a version with potentially infinite list of coefficients)
Line 1,143:
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?)coefficients. However, special care must be taken in order to write it, because the way Perl 6 implements lists is not optimized for this kind of treatment. [[Lisp]]-style 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 }
Line 1,161:
{{out}}
<pre>128</pre>
 
One advantage of using the composition operator is that it allows for the use of an infinite list of coefficients.
<lang perl6>sub horner ( @coeffs, $x ) {
map { .(0) }, [\o] map { $_ + $x * * }, @coeffs;
}
say horner( [ 1 X/ (1, |[\*] 1 .. *) ], i*pi )[20];
</lang>
{{out}}
<pre>-0.999999999924349-5.28918515954219e-10i</pre>
 
=={{header|PHP}}==
1,935

edits