On Rosetta (https://rosettacode.org/wiki/Continued_fraction#Perl )
there is the perl solution to evaluating Continuous fractions.
The code given is: (<===== comments added by me)
sub continued_fraction {
my ($a, $b, $n) = (@_[0,1], $_[2] // 100);
#<========= what is $_[2] // 100 ??
$a->() + ($n && $b->() / continued_fraction($a, $b, $n-1));
}
printf "√2 ≈ %.9f\n", continued_fraction do { my $n; sub
+{ $n++ ? 2 : 1 } }, sub { 1 }; # <===== Note there is no third arg p
+assed
printf "e ≈ %.9f\n", continued_fraction do { my $n; sub { $n++
+ || 2 } }, do { my $n; sub { $n++ || 1 } }; # <===== Note there is no
+ third arg passed
printf "π ≈ %.9f\n", continued_fraction do { my $n; sub {
+ $n++ ? 6 : 3 } }, do { my $n; sub { (2*$n++ + 1)**2 } }, 1_000; #<==
+== Here there is a 3rd arg
printf "π/2 ≈ %.9f\n", continued_fraction do { my $n; sub {
+ 1/($n++ || 1) } }, sub { 1 }, 1_000; #<==== Here there is a 3rd arg
The output shown on Rosetta is correct
.
My TWO questions are:
1) Why can they pass in two arguments sometimes (two function refs) and three arguments other times (two function refs, and an integer count?
2) What value does the expression $_[2] // 100 assign to $n ?
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.