Pascal's triangle: Difference between revisions

Content added Content deleted
(Perl →‎one-liner: use implicit parameters instead of explicit signature for improved readability)
Line 2,012: Line 2,012:


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:
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], -> @p { [0, @p Z+ @p, 0] } ... * }
<lang perl6>sub pascal { [1], { [0, @^p Z+ @^p, 0] } ... * }


.say for pascal[^10];</lang>
.say for pascal[^10];</lang>
Line 2,020: Line 2,020:
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.
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], -> @p { [0, @p Z+ @p, 0] } ... *;
<lang perl6>constant Pascal = [1], { [0, @^p Z+ @^p, 0] } ... *;


.say for Pascal[^10];</lang>
.say for Pascal[^10];</lang>