1. my class Bag does Baggy {
  2. has Int $!total;
  3. has $!WHICH;
  4. #--- introspection methods
  5. multi method WHICH(Bag:D:) {
  6. nqp::if(
  7. nqp::attrinited(self,Bag,'$!WHICH'),
  8. $!WHICH,
  9. $!WHICH := self!WHICH
  10. )
  11. }
  12. method total(Bag:D: --> Int:D) {
  13. nqp::if(
  14. nqp::attrinited(self,Bag,'$!total'),
  15. $!total,
  16. $!total := Rakudo::QuantHash.BAG-TOTAL(self.raw_hash)
  17. )
  18. }
  19. #--- object creation methods
  20. multi method new(Bag:_:) {
  21. nqp::if(
  22. nqp::eqaddr(self.WHAT,Bag),
  23. bag(),
  24. nqp::create(self)
  25. )
  26. }
  27. #--- interface methods
  28. method SET-SELF(Bag:D: \elems) {
  29. nqp::if(
  30. nqp::elems(elems),
  31. nqp::stmts( # need to have allocated %!elems
  32. nqp::bindattr(%!elems,Map,'$!storage',elems),
  33. self
  34. ),
  35. bag()
  36. )
  37. }
  38. multi method DELETE-KEY(Bag:D: \k) {
  39. X::Immutable.new(method => 'DELETE-KEY', typename => self.^name).throw;
  40. }
  41. #--- selection methods
  42. multi method grabpairs(Bag:D: $count?) {
  43. X::Immutable.new( method => 'grabpairs', typename => self.^name ).throw;
  44. }
  45. #--- coercion methods
  46. multi method Bag(Bag:D:) { self }
  47. multi method Mix(Bag:D:) {
  48. nqp::p6bindattrinvres(nqp::create(Mix),Mix,'%!elems',%!elems)
  49. }
  50. method clone() { nqp::clone(self) }
  51. proto method classify-list(|) {
  52. X::Immutable.new(:method<classify-list>, :typename(self.^name)).throw;
  53. }
  54. proto method categorize-list(|) {
  55. X::Immutable.new(:method<categorize-list>, :typename(self.^name)).throw;
  56. }
  57. }