Skip to content

Instantly share code, notes, and snippets.

@lizmat
Created May 12, 2014 23:34
Show Gist options
  • Save lizmat/80b8c5b3a02f8a742c0c to your computer and use it in GitHub Desktop.
Save lizmat/80b8c5b3a02f8a742c0c to your computer and use it in GitHub Desktop.
diff for making BagHash<unknown_key>-- return Int rather than 0
diff --git a/src/core/BagHash.pm b/src/core/BagHash.pm
index 21a35b8..960ea99 100644
--- a/src/core/BagHash.pm
+++ b/src/core/BagHash.pm
@@ -1,39 +1,31 @@
-my class BagHash does Baggy {
+my class BagValue is Int {
+ has $!hash;
+ has $!key;
+
+ submethod BUILD (:$!hash,:$!key) {}
- method at_key($k) {
- Proxy.new(
- FETCH => {
- my $key := $k.WHICH;
- %!elems.exists_key($key) ?? %!elems{$key}.value !! 0;
- },
- STORE => -> $, $value is copy {
- if $value > 0 {
- (%!elems{$k.WHICH} //= ($k => 0)).value = $value;
- }
- elsif $value == 0 {
- self.delete_key($k);
- }
- else {
- $value = 0;
- }
- $value;
- }
- );
+ method STORE ($value) {
+ ($!hash{$!key.WHICH} //= ($!key => 0)).value = $value;
}
+}
+
+my class BagHash does Baggy {
+
+ method at_key($key) { BagValue.new(:hash(%!elems),:$key) }
method delete($k) { # is DEPRECATED doesn't work in settings
DEPRECATED("the :delete adverb");
self.delete_key($k);
}
method delete_key($k) {
- my $key := $k.WHICH;
- if %!elems.exists_key($key) {
- my $value = %!elems{$key}.value;
- %!elems.delete_key($key);
+ my $keyw := $k.WHICH;
+ if %!elems.exists_key($keyw) {
+ my $value = %!elems{$keyw}.value;
+ %!elems.delete_key($keyw);
$value;
}
else {
- 0;
+ Int;
}
}
@@ -52,4 +44,34 @@ my class BagHash does Baggy {
method MixHash { MixHash.new-fp(%!elems.values) }
}
+multi postcircumfix:<{ }> (BagHash:D $self, $key) {
+ my $hash := nqp::getattr($self,BagHash,'%!elems');
+ my $keyw := $key.WHICH;
+ $hash.exists_key($keyw) ?? $hash{$keyw}.value !! Int;
+}
+multi prefix:<++> (BagValue:D $self) {
+ my $hash := nqp::getattr($self,BagValue,'$!hash');
+ my $key := nqp::getattr($self,BagValue,'$!key');
+ ($hash{$key.WHICH} //= ($key => 1)).value;
+}
+multi prefix:<--> (BagValue:D $self) {
+ my $hash := nqp::getattr($self,BagValue,'$!hash');
+ my $keyw := nqp::getattr($self,BagValue,'$!key').WHICH;
+ my $value = $hash.exists_key($keyw) ?? --($hash{$keyw}.value) !! Int;
+ $hash.delete_key($keyw) if $value.defined and $value == 0;
+ $value;
+}
+multi postfix:<++> (BagValue:D $self) {
+ my $hash := nqp::getattr($self,BagValue,'$!hash');
+ my $key := nqp::getattr($self,BagValue,'$!key');
+ ($hash{$key.WHICH} //= ($key => 0)).value++ || Int;
+}
+multi postfix:<--> (BagValue:D $self) {
+ my $hash := nqp::getattr($self,BagValue,'$!hash');
+ my $keyw := nqp::getattr($self,BagValue,'$!key').WHICH;
+ my $value = $hash.exists_key($keyw) ?? ($hash{$keyw}.value)-- !! Int;
+ $hash.delete_key($keyw) if $value.defined and $value == 1;
+ $value;
+}
+
# vim: ft=perl6 expandtab sw=4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment