Add | and & operations for sets

This commit is contained in:
K. Lange 2021-01-11 21:46:47 +09:00
parent dc56d7b2ea
commit ef92ace5a7
2 changed files with 36 additions and 2 deletions

View File

@ -58,7 +58,7 @@ const char krk_builtinsSrc[] =
" return v in self._dict\n"
" def __str__(self): return self.__repr__()\n"
" def __repr__(self):\n"
" if self.__inrepr: return '{}' # sets are supposed to be unhashable, but whatever\n"
" if self.__inrepr: return '{}'\n"
" let b='{'+', '.join([repr(k) for k in self._dict.keys()])+'}'\n"
" self.__inrepr = 0\n"
" return b\n"
@ -68,6 +68,23 @@ const char krk_builtinsSrc[] =
" return self._dict.__len__()\n"
" def __iter__(self):\n"
" return self._dict.keys().__iter__()\n"
" def __or__(self, o):\n"
" if not isinstance(o, set):\n"
" raise TypeError()\n"
" let b = set()\n"
" for k in self:\n"
" b.add(k)\n"
" for k in o:\n"
" b.add(k)\n"
" return b\n"
" def __and__(self, o):\n"
" if not isinstance(o, set):\n"
" raise TypeError()\n"
" let b = set()\n"
" for k in self:\n"
" if k in o:\n"
" b.add(k)\n"
" return b\n"
"\n"
"__builtins__.set = set\n"
"\n"

View File

@ -57,7 +57,7 @@ class set():
return v in self._dict
def __str__(self): return self.__repr__()
def __repr__(self):
if self.__inrepr: return '{}' # sets are supposed to be unhashable, but whatever
if self.__inrepr: return '{}'
let b='{'+', '.join([repr(k) for k in self._dict.keys()])+'}'
self.__inrepr = 0
return b
@ -67,6 +67,23 @@ class set():
return self._dict.__len__()
def __iter__(self):
return self._dict.keys().__iter__()
def __or__(self, o):
if not isinstance(o, set):
raise TypeError()
let b = set()
for k in self:
b.add(k)
for k in o:
b.add(k)
return b
def __and__(self, o):
if not isinstance(o, set):
raise TypeError()
let b = set()
for k in self:
if k in o:
b.add(k)
return b
__builtins__.set = set