Pascal's triangle: Difference between revisions

→‎using a lazy sequence generator: show a version with implicit $_, which I think looks better in this case.
(Add Maple implementation)
(→‎using a lazy sequence generator: show a version with implicit $_, which I think looks better in this case.)
Line 2,829:
 
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, |$prev_ Z+ |$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. Here we use the <tt>@</tt> sigil to indicate that the sequence should cache its values for reuse, and use an explicit parameter <tt>$prev</tt> for variety:
 
<lang perl6>constant @pascal = [1], -> $prev { [0, |$prev Z+ |$prev, 0] } ... *;
Anonymous user