Continued fraction: Difference between revisions

→‎{{header|Perl}}: using persistent private variables
(→‎{{header|Perl}}: shortening a bit + computing 2*pi instead of pi to make things less boring)
(→‎{{header|Perl}}: using persistent private variables)
Line 640:
=={{header|Perl}}==
{{trans|Perl6}}
Perl5 does not really support lazy lists sobut we'll can use closures to do something similar.
 
With a recent version of Perl (5.10 or above), we can also use persistent private variables (see perlsub). We just need to declare this with the 'use feature "state"' pragma.
 
In this example we'll show both methods.
 
<lang perl>sub continued_fraction {
Line 654 ⟶ 658:
}
# using closures
printf "√2 ≈ %.9f\n", continued_fraction do { my $n; sub { $n++ ? 2 : 1 } }, sub { 1 };
 
printf "e ≈ %.9f\n", continued_fraction do { my $n; sub { $n++ ? $n-1 : 2 } }, do { my $n; sub { $n++ ? $n-1 : 1 } };
# using persistent private variables
printf "τ ≈ %.9f\n", continued_fraction sub { 6 }, do { my $n; sub { $n++ ? (2*$n - 1)**2 : 2 } }, 1_000;
use feature 'state'
printf "e ≈ %.9f\n", continued_fraction dosub { mystate $n; sub { $n++ ? $n-1 : 2 } }, dosub { mystate $n; sub { $n++ ? $n-1 : 1 } };
printf "τ ≈ %.9f\n", continued_fraction sub { 6 }, dosub { mystate $n; sub { $n++ ? (2*$n - 1)**2 : 2 } }, 1_000;
</lang>
{{out}}
1,935

edits