Pascal's triangle: Difference between revisions

No edit summary
Line 2,439:
 
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], -> $prev { [0, @^p|$prev Z+ @^p|$prev, 0] } ... * }
 
.say for pascal[^10];</lang>
 
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 givesHere we use the compiler<tt>@</tt> moresigil latitudeto inindicate whetherthat tothe cachesequence orshould recalculatecache intermediateits values for reuse:
<small>(See [http://perlgeek.de/blog-en/perl-6/pascal-triangle.writeback this blog post] for a partial explanation of how this one-liner works.)</small>
 
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>
 
<lang perl6>constant Pascal@pascal = [1], -> $prev { [0, @^p|$prev Z+ @^p|$prev, 0] } ... *;
<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>
.say for Pascal@pascal[^10];</lang>
 
NonSince we use ordinary subscripting, non-positive inputs throw an index-out-of-bounds error.
 
=== recursive ===
Anonymous user