Damian Conway wrote:

Et voilà:
Or, of those who prefer their code sanely formatted:


    sub part ($classifier, *@list) {
        my &classify := convert_to_sub($classifier);
        my @parts;
        for @list -> $nextval {
            my $index = try{ classify($nextval) } // next;
            push @parts[$index], $nextval;
        }
        return @parts;
    }

    sub convert_to_sub ($classifier is topic) is cached {
        when Code  { return $classifier }

        when Array {
            my @classifiers = map {convert_to_code($_)} @$classifier;
            return sub ($nextval) {
                for @classifiers.kv -> $index, &test {
                    return $index if test($nextval);
                }
                return;
            }
        }

        when Hash  {
            my %classifiers = map { convert_to_code(.key) => .value } %$classifier;
            return sub ($nextval) {
                my @indices = map { defined .key()($nextval) ?? .value :: () } %classifiers;
                return @indices ?? any(@indices) :: undef;
            }
        }

        default    { croak "Invalid classifier (must be closure, array, or hash)" }
    }


Damian

Reply via email to