Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Bring loads of methods for EnumMap (previously Mapping) and Hash back…
…. Rewrite those that used to be in PIR into Perl 6. Some that don't do mutations but were only in Hash are now in both; I see no good reason for them not to also be in EnumMap.
  • Loading branch information
jnthn committed Feb 23, 2010
1 parent 9b33a8d commit 6884da0
Show file tree
Hide file tree
Showing 2 changed files with 103 additions and 0 deletions.
57 changes: 57 additions & 0 deletions src/core/EnumMap.pm
Expand Up @@ -20,6 +20,47 @@ class EnumMap does Associative {
}
}

multi method ACCEPTS(Regex $topic) {
any(@.keys) ~~ $topic;
}

multi method ACCEPTS(%topic) {
@.keys.sort eqv %topic.keys.sort;
}

multi method ACCEPTS(@topic) {
self.contains(any(@topic))
}

multi method ACCEPTS($topic) {
self.contains($topic)
}

method contains($key) {
# Wish we could do pir:: for keyed things. *sigh*
?(Q:PIR {
$P0 = find_lex '$key'
$P1 = find_lex 'self'
$P1 = getattribute $P1, '$!storage'
$I0 = exists $P1[$P0]
%r = box $I0
})
}
method fmt($format = "%s\t%s", $sep = "\n") {
self.pairs.map({ .fmt($format) }).join($sep)
}
multi method invert () is export {
gather {
for @.pairs {
for @( .value ) -> $i {
take ($i => .key)
}
}
}
}
method iterator() {
# We just work off the low-level Parrot iterator.
my $iter = pir::iter__PP($!storage);
Expand All @@ -44,6 +85,22 @@ class EnumMap does Associative {
}
}

method pairs() {
self.iterator()
}

method perl() {
return '{' ~ self.pairs.map({ .perl }).join(", ") ~ '}';
}

method reverse() {
my %result;
for self.pairs() -> $p {
%result{$p.value} = $p.key;
}
%result
}

method values() {
self.iterator.map({ $^pair.value })
}
Expand Down
46 changes: 46 additions & 0 deletions src/core/Hash.pm
Expand Up @@ -51,4 +51,50 @@ role Hash is EnumMap {
}
self
}

method delete(*@keys) {
my @deleted;
for @keys -> $k {
@deleted.push(self{$k});
Q:PIR {
$P0 = find_lex '$k'
$P1 = find_lex 'self'
$P1 = getattribute $P1, '$!storage'
delete $P1[$P0]
}
}
@deleted
}
method push(*@values) {
my $previous;
my $has_previous;
for @values -> $e {
if $has_previous {
self!push_construct($previous, $e);
$has_previous = 0;
} elsif $e ~~ Pair {
self!push_construct($e.key, $e.value);
} else {
$previous = $e;
$has_previous = 1;
}
}
if $has_previous {
warn "Trailing item in Hash.push";
}
}
# push a value onto a hash Objectitem, constructing an array if necessary
method !push_construct(Mu $key, Mu $value) {
if self.exists($key) {
if self.{$key} ~~ Array {
self.{$key}.push($value);
} else {
self.{$key} = [ self.{$key}, $value];
}
} else {
self.{$key} = $value;
}
}
}

0 comments on commit 6884da0

Please sign in to comment.