#!/usr/bin/pugs use v6-alpha; #P01 (*) Find the last box of a list. # Example: # * (my-last '(a b c d)) # (D) [-1].say; #P02 (*) Find the last but one box of a list. # Example: # * (my-but-last '(a b c d)) # (C D) [-2, -1].perl.say; #P03 (*) Find the K'th element of a list. # The first element in the list is number 1. # Example: # * (element-at '(a b c d e) 3) # C [2].perl.say; #P04 (*) Find the number of elements of a list. .elems.say; #P05 (*) Reverse a list. .reverse.perl.say; #P06 (*) Find out whether a list is a palindrome. # A palindrome can be read forward or backward; e.g. (x a m a x). for [], [] -> $array { if $array.reverse ~~ $array { say $array.perl ~ " is a palindrome"; } else { say $array.perl ~ " is not a palindrome"; } } #P07 (**) Flatten a nested list structure. # Transform a list, possibly holding lists as elements into a `flat' list by # replacing each list with its elements (recursively). # courtesy of Wim Vanderbauwhede from the perl6-users list my $flatten = -> $x { $x.isa(Array) ?? ( map $flatten, $x ) !! $x }; my @flattened = map $flatten, ('a', ['b', ['c', 'd', 'e']]); @flattened.perl.say; #P08 (**) Eliminate consecutive duplicates of list elements. # If a list contains repeated elements they should be replaced with a single # copy of the element. The order of the elements should not be changed. # Example: # * (compress '(a a a a b c c a a d e e e e)) # (a b c a d E) my $compress = do { my $previous; $compress = sub ($x) { if $x ne $previous { $previous = $x; return $x; } else { return; } }; } my @compressed = map $compress, ; @compressed.perl.say; #P09 (**) Pack consecutive duplicates of list elements into sublists. # If a list contains repeated elements they should be placed in separate sublists. # # Example: # * (pack '(a a a a b c c a a d e e e e)) # ((A A A A) (B) (C C) (A A) (D) (E E E E)) my @packed; { my @sublist; my $previous; for -> $x { if $x eq $previous { @sublist.push($x); next; } $previous = $x; if @sublist { @packed.push([@sublist]); @sublist = $x; } } @packed.push([@sublist]); } @packed.perl.say;