Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Port Bag from niecza
  • Loading branch information
Tadeusz Sośnierz committed Mar 1, 2012
1 parent bc82980 commit 60a6a55
Show file tree
Hide file tree
Showing 3 changed files with 54 additions and 1 deletion.
52 changes: 52 additions & 0 deletions src/core/Bag.pm
@@ -0,0 +1,52 @@
my role Baggy { Any }

my class Bag is Iterable does Associative does Baggy {
has %!elems; # should be UInt

method keys { %!elems.keys }
method values { %!elems.values }
method elems returns Int { [+] self.values }
method exists($a) returns Bool { %!elems.exists($a) }
method Bool { %!elems.Bool }
method Numeric { self.elems }
method hash { %!elems.hash }
method at_key($k) { +(%!elems{$k} // 0) }
method exists_key($k) { self.exists($k) }

# Constructor
method new(*@args --> Bag) {
my %e;
sub register-arg($arg) {
given $arg {
when Pair { if .value { if %e.exists(.key) { %e{.key} += .value } else { %e{.key} = .value } } }
when Set | KeySet { for .keys -> $key { %e{$key}++; } }
when Associative { for .pairs -> $p { register-arg($p) } }
when Positional { for .list -> $p { register-arg($p) } }
default { %e{$_}++; }
}
}

for @args {
register-arg($_);
}
self.bless(*, :elems(%e));
}

submethod BUILD (:%!elems) { }

multi method Str(Any:D $ : --> Str) { "bag({ self.pairs>>.perl.join(', ') })" }
multi method gist(Any:D $ : --> Str) { "bag({ self.pairs>>.gist.join(', ') })" }
multi method perl(Any:D $ : --> Str) { 'Bag.new(' ~ %!elems.perl ~ ')' }

method iterator() { %!elems.pairs.iterator }
method list() { %!elems.keys }
method pairs() { %!elems.pairs }

method pick($count = 1) { my $kb = KeyBag.new(self); $kb.pick($count); }
method roll($count = 1) { my $kb = KeyBag.new(self); $kb.roll($count); }
}

sub bag(*@a) returns Bag {
Bag.new(|@a);
}

2 changes: 1 addition & 1 deletion src/core/stubs.pm
Expand Up @@ -4,7 +4,7 @@
# in Perl6::Metamodel for now, though should be a BEGIN block in CORE.setting
# in the end.
my class Whatever { ... }
my class Bag is Iterable does Associative { }
my class Bag { ... }
my class KeyBag is Iterable does Associative { }
my class KeySet is Iterable does Associative { }
my class KeyHash is Iterable does Associative { }
Expand Down
1 change: 1 addition & 0 deletions tools/build/Makefile.in
Expand Up @@ -222,6 +222,7 @@ CORE_SOURCES = \
src/core/EXPORTHOW.pm \
src/core/Pod.pm \
src/core/Set.pm \
src/core/Bag.pm \
src/core/ObjAt.pm \
src/core/operators.pm \
src/core/metaops.pm \
Expand Down

0 comments on commit 60a6a55

Please sign in to comment.