Anonymous user
Pascal's triangle: Difference between revisions
→{{header|Perl 6}}: rearrange, categorize & clean up the solutions
(Perl →one-liner: use implicit parameters instead of explicit signature for improved readability) |
(→{{header|Perl 6}}: rearrange, categorize & clean up the solutions) |
||
Line 1,987:
=={{header|Perl 6}}==
{{trans|Haskell}} (the short version)▼
=== using a lazy sequence generator ===
The following routine returns a lazy list of lines using the sequence operator (<tt>...</tt>). With a lazy result you need not tell the routine how many you want; you can just use a slice subscript to get the first N lines:▼
<lang perl6>sub pascal { [1], { [0, @^p Z+ @^p, 0] } ... * }▼
.say for pascal[^10];</lang>▼
<small>(See [http://perlgeek.de/blog-en/perl-6/pascal-triangle.writeback this blog post] for a partial explanation of how this one-liner
One problem with the routine above is that it might recalculate the sequence each time you call it. Slightly more idiomatic would be to define the sequence as a lazy constant, which gives the compiler more latitude in whether to cache or recalculate intermediate values
<lang perl6>constant Pascal = [1], { [0, @^p Z+ @^p, 0] } ... *;▼
.say for Pascal[^10];</lang>▼
<small>(A desperate garbage collector may still trim an overly long lazy constant, since it can always be recreated later, assuming the programmer didn't lie about its constancy.)</small>
Non-positive inputs throw a multiple-dispatch error.
Line 1,997 ⟶ 2,017:
}
=== iterative ===
{{trans|Perl}}
<lang perl6>sub pascal ($n where $n >= 1) {
say my @last = 1;
for 1 .. $n - 1 -> $row {
say @last
}
}
}</lang>▼
▲=== one-liner ===
▲The following routine returns a lazy list of lines using the sequence operator (<tt>...</tt>). With a lazy result you need not tell the routine how many you want; you can just use a slice subscript to get the first N lines:
▲<lang perl6>sub pascal { [1], { [0, @^p Z+ @^p, 0] } ... * }
▲.say for pascal[^10];</lang>
▲See http://perlgeek.de/blog-en/perl-6/pascal-triangle.writeback for a partial explanation of how this one-liner example works.
▲One problem with the routine above is that it might recalculate the sequence each time you call it. Slightly more idiomatic would be to define the sequence as a lazy constant, which gives the compiler more latitude in whether to cache or recalculate intermediate values. (A desperate garbage collector can trim an overly long lazy constant, since it can always be recreated later, assuming the programmer didn't lie about its constancy.) In that sense, this is a better translation of the Haskell too.
▲<lang perl6>constant Pascal = [1], { [0, @^p Z+ @^p, 0] } ... *;
▲.say for Pascal[^10];</lang>
▲Output:
<pre>1
1 1
|