Pascal's triangle: Difference between revisions
Content added Content deleted
No edit summary |
(→using a lazy sequence generator: glrify) |
||
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,
.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
▲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>▼
=== recursive ===
|