Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Perl 6, how can I replicate the behavior of Perl's List::Util::all?

I am trying to use a Junction to replicate behavior I am used to in Perl from List::Util::all.

I am using the all junction in the following statement:

# does not work
return not know(@possible-dates) and not know tell day all(@possible-dates);

not knowing what any of these functions do, I assumed that this statement would be equivalent to the following:

# works
my Bool $r = not know @possible-dates;
for @possible-dates -> $date {
  $r = $r && not know tell day $date;
}

return $r;

The for loop version returns the correct result, the junction version does not and I am trying to understand why.

Full code below to inform what all of the functions do:

my @dates = <May 15>, <May 16>, <May 19>, <June 17>, <June 18>, 
  <July 14>, <July 16>, <August 14>, <August 15>, <August 17>;

sub day (@date) { @date[1] }
sub month (@date) { @date[0] }

sub tell($data) {
  @dates.grep({ day($_) eq $data or month($_) eq $data });
}

sub know(@possible-dates) { @possible-dates.elems == 1 }

sub statement-one(@date) {
  my @possible-dates = tell month @date;

  # why is this not the same as below?
  return not know(@possible-dates) 
    and not know tell day all(@possible-dates);

  # my Bool $r = not know @possible-dates;
  # for @possible-dates -> $date {
  #   $r = $r && not know tell day $date;
  # }
  #
  # return $r;
}

sub statement-two(@date) {
  my @possible-dates = tell day @date;

  not know(@possible-dates) 
    and know @possible-dates.grep(&statement-one);
}

sub statement-three(@date) {
  my @possible-dates = tell month @date;

  know @possible-dates.grep(&statement-two);
}

sub cheryls-birthday() {
  @dates.grep({ 
    statement-one($_) 
      and statement-two($_) 
      and statement-three($_) 
  });
}

say cheryls-birthday();
like image 660
Hunter McMillen Avatar asked May 01 '18 12:05

Hunter McMillen


1 Answers

I guess the easiest answer is to do a

zef install List::Util

and then put a:

use List::Util 'any';

in your code. There are some subtle differences between Perl 6's any and the any with Perl 5 semantics that is provided by http://modules.raku.org/dist/List::Util:cpan:ELIZABETH .

In Perl 6, any returns a Junction object. In Perl 5 any is a function that you call on a list with a block to execute on.

like image 106
Elizabeth Mattijsen Avatar answered Oct 05 '22 02:10

Elizabeth Mattijsen