Advertisement
Guest User

Untitled

a guest
Apr 7th, 2021
486
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 6 1.88 KB | None | 0 0
  1. # Raku feature: Lazy list. This construct will repeat 99 to 0
  2. # and then start over at 99 ad infintum when iterated
  3.  
  4. my @indices = flat (99...0) xx Inf;
  5.  
  6. # for every index, generate the "xx bottles of beer"
  7. # when using double quotes the Raku parser interprets
  8. # code in curlies as, well, code and embeds the return
  9. # value within the string
  10. # in the first block we see an ordinary logical or
  11. # in the second we see a ternary
  12.  
  13. my @bottles = @indices.map: -> $n {
  14.     "{$n || 'no more'} bottle{ $n == 1 ?? '' !! 's' } of beer"
  15. };
  16.  
  17. # generate the first line of each verse
  18. # Raku also has simple string interpolation
  19.  
  20. my @beers-on-the-wall = @bottles.map: -> $bottles-of-beer {
  21.     "$bottles-of-beer on the wall, $bottles-of-beer\n".tc
  22. };
  23.  
  24. # Here we see the Z operator at work. It zips together two (or more) lists and returns one value from each.
  25.  
  26. # generate the second line of each verse
  27. # Note the deconstruction of the incoming sublist into two variables
  28.  
  29. my @beers-to-get = ( @indices Z @bottles.skip ).map: -> ( $beers-on-the-wall, $beers-available ) {
  30.     "{ $beers-on-the-wall ?? 'Take one down and pass it around' !! 'Go to the store and buy some more' }, $beers-available on the wall.\n"
  31. };
  32.  
  33. # generate the verses
  34. # Here we are not deconstructing the result of the zip operation, so we get a list we can just join
  35. my @lyrics = ( @beers-on-the-wall Z @beers-to-get).map: -> @parts {
  36.     @parts.join
  37. }
  38.  
  39. # This is the first time any of the code above actually runs because everything is lazy
  40. # Only when we really ask for values the code runs
  41. # Here we ask for the first 100 values which is one time the whole song
  42. # The ^100 is just a short form to write the range 0..99
  43.  
  44. .say for @lyrics[ ^100 ];
  45.  
  46. # Now, here's the kicker. Since the original @indices sequence is infinite we can easily
  47. # display the song twice
  48.  
  49. .say for @lyrics[ ^200 ];
  50.  
  51. # Or even forever
  52.  
  53. .say for @lyrics;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement