From bbad46092aeb8c6c6cf3d51ceb6f4643f9550040 Mon Sep 17 00:00:00 2001 From: DoDaek Date: Tue, 17 Sep 2019 21:06:03 +0900 Subject: [PATCH 1/2] set: Implement __or__ of set --- py/set.go | 14 ++++++++++++++ py/tests/set.py | 17 +++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/py/set.go b/py/set.go index f38b32ff..3b35bf8d 100644 --- a/py/set.go +++ b/py/set.go @@ -125,6 +125,20 @@ func (s *Set) M__and__(other Object) (Object, error) { return ret, nil } +func (s *Set) M__or__(other Object) (Object, error) { + ret := s + b, ok := other.(*Set) + if !ok { + return nil, ExceptionNewf(TypeError, "unsupported operand type(s) for &: '%s' and '%s'", s.Type().Name, other.Type().Name) + } + for i := range b.items { + if _, ok := s.items[i]; !ok { + ret.items[i] = SetValue{} + } + } + return ret, nil +} + // Check interface is satisfied var _ I__len__ = (*Set)(nil) var _ I__bool__ = (*Set)(nil) diff --git a/py/tests/set.py b/py/tests/set.py index e1500ed1..e46b412a 100644 --- a/py/tests/set.py +++ b/py/tests/set.py @@ -13,4 +13,21 @@ assert 2 in d assert 3 in d +doc="__or__" +a = {1, 2, 3} +b = {2, 3, 4, 5} +c = a.__or__(b) +assert 1 in c +assert 2 in c +assert 3 in c +assert 4 in c +assert 5 in c + +d = a | b +assert 1 in c +assert 2 in c +assert 3 in c +assert 4 in c +assert 5 in c + doc="finished" \ No newline at end of file From 8cc93532c1b7f5de3840e52a367f17017936e3a3 Mon Sep 17 00:00:00 2001 From: DoDaek Date: Tue, 17 Sep 2019 21:34:27 +0900 Subject: [PATCH 2/2] set: create a new instance for the value returned --- py/set.go | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/py/set.go b/py/set.go index 3b35bf8d..af4eb4e5 100644 --- a/py/set.go +++ b/py/set.go @@ -126,11 +126,14 @@ func (s *Set) M__and__(other Object) (Object, error) { } func (s *Set) M__or__(other Object) (Object, error) { - ret := s + ret := NewSet() b, ok := other.(*Set) if !ok { return nil, ExceptionNewf(TypeError, "unsupported operand type(s) for &: '%s' and '%s'", s.Type().Name, other.Type().Name) } + for j := range s.items { + ret.items[j] = SetValue{} + } for i := range b.items { if _, ok := s.items[i]; !ok { ret.items[i] = SetValue{}