sets.sf 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. #!/usr/bin/ruby
  2. #
  3. ## https://rosettacode.org/wiki/MySet#Sidef
  4. #
  5. class MySet(*set) {
  6. method init {
  7. var elems = set;
  8. set = Hash.new;
  9. elems.each { |e| self += e }
  10. }
  11. method +(elem) {
  12. set{elem} = elem;
  13. self;
  14. }
  15. method del(elem) {
  16. set.delete(elem);
  17. }
  18. method has(elem) {
  19. set.has_key(elem);
  20. }
  21. method ∪(MySet that) {
  22. MySet(set.values..., that.values...);
  23. }
  24. method ∩(MySet that) {
  25. MySet(set.keys.grep{ |k| k ∈ that } \
  26. .map { |k| set{k} }...);
  27. }
  28. method ∖(MySet that) {
  29. MySet(set.keys.grep{|k| !(k ∈ that) } \
  30. .map {|k| set{k} }...);
  31. }
  32. method ^(MySet that) {
  33. var d = ((self ∖ that) ∪ (that ∖ self));
  34. MySet(d.values...);
  35. }
  36. method count { set.len }
  37. method ≡(MySet that) {
  38. (self ∖ that -> count.is_zero) && (that ∖ self -> count.is_zero);
  39. }
  40. method values { set.values }
  41. method ⊆(MySet that) {
  42. that.set.keys.each { |k|
  43. k ∈ self || return false;
  44. }
  45. return true;
  46. }
  47. method to_s {
  48. "Set{" + set.values.map{|e| "#{e}"}.sort.join(', ') + "}"
  49. }
  50. }
  51. class Object {
  52. method ∈(MySet set) {
  53. set.has(self);
  54. }
  55. }
  56. #
  57. ## Testing
  58. #
  59. var x = MySet(1, 2, 3);
  60. 5..7 -> each { |i| x += i };
  61. var y = MySet(1, 2, 4, x);
  62. say "set x is: #{x}";
  63. say "set y is: #{y}";
  64. [1,2,3,4,x].each { |elem|
  65. say ("#{elem} is ", elem ∈ y ? '' : 'not', " in y");
  66. }
  67. var (w, z);
  68. say ("union: ", x ∪ y);
  69. say ("intersect: ", x ∩ y);
  70. say ("z = x ∖ y = ", z = (x ∖ y) );
  71. say ("y is ", x ⊆ y ? "" : "not ", "a subset of x");
  72. say ("z is ", x ⊆ z ? "" : "not ", "a subset of x");
  73. say ("z = (x ∪ y) ∖ (x ∩ y) = ", z = ((x ∪ y) ∖ (x ∩ y)));
  74. say ("w = x ^ y = ", w = (x ^ y));
  75. say ("w is ", w ≡ z ? "" : "not ", "equal to z");
  76. say ("w is ", w ≡ x ? "" : "not ", "equal to x");