Permalink
Browse files

Port KeySet from niecza

  • Loading branch information...
1 parent d524c6a commit bb2e1f815127e13ae9170ddc684337d0767fa7be @tadzik tadzik committed Mar 1, 2012
Showing with 49 additions and 1 deletion.
  1. +48 −0 src/core/Set.pm
  2. +1 −1 src/core/stubs.pm
View
@@ -59,3 +59,51 @@ my class Set is Iterable does Associative {
sub set(*@args) {
Set.new(@args);
}
+
+class KeySet is Iterable does Associative {
+ has %!elems;
+
+ method keys { %!elems.keys }
+ method values { %!elems.values }
+ method elems returns Int { %!elems.elems }
+ method exists($a) returns Bool { %!elems.exists($a) && %!elems{$a} }
+ method Bool { %!elems.Bool }
+ method Numeric { %!elems.Numeric }
+ method hash { %!elems.hash }
+ method at_key($k) {
+ Proxy.new(FETCH => { %!elems.exists($k) ?? True !! False },
+ STORE => -> $, $value { if $value { %!elems{$k} = True } else { %!elems.delete($k) }});
+ }
+ method exists_key($k) { self.exists($k) }
+ method delete_key($k) { %!elems.delete($k) }
+
+ # Constructor
+ method new(*@args --> KeySet) {
+ my %e;
+ sub register-arg($arg) {
+ given $arg {
+ when Pair { %e{.key} = True; }
+ when Set | KeySet { for .keys -> $key { %e{$key} = True; } }
+ when Associative { for .pairs -> $p { register-arg($p); } }
+ when Positional { for .list -> $p { register-arg($p); } }
+ default { %e{$_} = True; }
+ }
+ }
+
+ for @args {
+ register-arg($_);
+ }
+ self.bless(*, :elems(%e));
+ }
+
+ submethod BUILD (:%!elems) { }
+
+ submethod Str(Any:D $ : --> Str) { "keyset(< %!elems.keys() >)" }
+ submethod gist(Any:D $ : --> Str) { "keyset({ %!elems.keys».gist.join(', ') })" }
+ submethod perl(Any:D $ : --> Str) { 'KeySet.new(' ~ join(', ', map { .perl }, %!elems.keys) ~ ')' }
+
+ method iterator() { %!elems.keys.iterator }
+ method list() { %!elems.keys }
+ method pick($count = 1) { %!elems.keys.pick($count) }
+ method roll($count = 1) { %!elems.keys.roll($count) }
+}
View
@@ -6,7 +6,7 @@
my class Whatever { ... }
my class Bag { ... }
my class KeyBag { ... }
-my class KeySet is Iterable does Associative { }
+my class KeySet { ... }
my class KeyHash is Iterable does Associative { }
my class Seq is List does Positional { }
my class Exception { ... }

0 comments on commit bb2e1f8

Please sign in to comment.