feat: add Dict.concat/diff, Dict!.merge!/remove!

This commit is contained in:
Shunsuke Shibayama 2023-10-04 22:39:30 +09:00
parent 73958a3e56
commit 13a346e488
11 changed files with 223 additions and 6 deletions

View file

@ -4,4 +4,29 @@ dict = pyimport "Dict"
.Dict!: ClassType
.Dict! <: dict.Dict
.Dict!.
insert!: |K, V|(self: .Dict!, key: K, value: V) => NoneType
'''erg
dic = !{"a": 1}
dic.insert!("b", 2)
assert dic == {"a": 1, "b": 2}
'''
insert!: |K, V|(self: .Dict!(K, V), key: K, value: V) => NoneType
'''erg
dic = !{"a": 1}
x = dic.remove!("a")
assert dic == {}
assert x == 1
'''
remove!: |K, V|(self: .Dict!(K, V), key: K) => V or NoneType
'''erg
dic = !{"a": 1}
dic.update!({"b": 2})
dic.update!([("c", 3)])
assert dic == {"a": 1, "b": 2, "c": 3}
'''
update!: |K, V|(self: .Dict!(K, V), other: Iterable([K, V])) => NoneType
'''erg
dic = !{"a": 1}
dic.merge!({"b": 2})
assert dic == {"a": 1, "b": 2}
'''
merge!: |K, V|(self: .Dict!(K, V), other: .Dict!(K, V)) => NoneType

View file

@ -10,3 +10,13 @@
items: |K, V|(self: .Dict(K, V)) -> .DictItems(K, V)
keys: |K, V|(self: .Dict(K, V)) -> .DictKeys(K, V)
values: |K, V|(self: .Dict(K, V)) -> .DictValues(K, V)
'''erg
dic = {"a": 1, "b": 2}
assert dic.concat({"c": 3}) == {"a": 1, "b": 2, "c": 3}
'''
concat: (self: .Dict(K, V), other: .Dict(K, V)) -> .Dict(K, V)
'''erg
dic = {"a": 1, "b": 2}
assert dic.diff({"a": 2, "d": 4}) == {"b": 2}
'''
diff: (self: .Dict(K, V), other: .Dict(K, V)) -> .Dict(K, V)

View file

@ -1,2 +1,18 @@
class Dict(dict):
pass
def concat(self, other):
return Dict({**self, **other})
def diff(self, other):
return Dict({k: v for k, v in self.items() if k not in other})
# other: Iterable
def extend(self, other):
self.update(other)
# other: Dict
def merge(self, other):
self.update(other)
def insert(self, key, value):
self[key] = value
def remove(self, key):
res = self.get(key)
if res != None:
del self[key]
return res