Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- sub mygrep {
- my $code = shift;
- my @array;
- for (@_) {
- if ($code->($_)) {
- push @array, $_;
- }
- }
- return @array;
- }
- sub myany {
- my $code = shift;
- for (@_) {
- if ($code->($_)) {
- return 1; # true
- }
- }
- return; # false
- }
- sub mymap {
- my $code = shift;
- my @result;
- for (@_) {
- push @result, $code->($_);
- }
- return @result;
- }
- sub myreduce {
- my $code = shift;
- my $val = shift;
- for (@_) {
- local ($a, $b) = ($val, $_);
- $val = $code->($val, $_);
- }
- return $val;
- }
- sub mysort {
- my $code = shift;
- my @array = @_;
- for my $i (0..$#array) {
- for my $j (($i + 1)..$#array) {
- local ($a, $b) = ($array[$i], $array[$j]);
- if (!$code->($array[$i], $array[$j])) {
- ($array[$i], $array[$j]) = ($array[$j], $array[$i]);
- }
- }
- }
- return @array;
- }
- my @array = (1, 2, 3, 4, 5);
- print "@array\n";
- my @even = mygrep sub { $_ % 2 == 0 }, @array;
- my $any_even = (myany sub { $_ % 2 == 0 }, @array) ? "true" : "false";
- my @square = mymap sub { $_ ** 2 }, @array;
- print "@even\n";
- print "$any_even\n";
- print "@square\n";
- my $sum = myreduce sub { $a + $b }, @array;
- my $product = myreduce sub { $a * $b }, @array;
- my $max = myreduce sub { $a > $b ? $a : $b }, @array;
- my $min = myreduce sub { $a > $b ? $b : $a }, @array;
- print $sum, "\n";
- print $product, "\n";
- print $max, "\n";
- print $min, "\n";
- my @sorted = mysort sub { $a > $b }, @array;
- print "@sorted\n";
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement