Implement some primitive types methods

This commit is contained in:
Shunsuke Shibayama 2022-11-27 16:35:50 +09:00
parent 1a9ae3349d
commit 9ac8248609
3 changed files with 39 additions and 0 deletions

View file

@ -1,4 +1,8 @@
class Array(list):
def dedup(self):
return Array(list(set(self)))
def dedup_by(self, f):
return Array(list(set(map(f, self))))
def push(self, value):
self.append(value)
return self

View file

@ -10,3 +10,9 @@ class Nat(int):
def times(self, f):
for _ in range(self):
f()
def saturating_sub(self, other: Nat):
if self > other:
return self - other
else:
return 0

View file

@ -8,3 +8,32 @@ class Str(str):
return Str(s)
else:
return Error("Str can't be other than str")
def get(self, i: int):
if len(self) > i:
return Str(self[i])
else:
return None
class StrMut(Str):
def try_new(s: str):
if isinstance(s, str):
return StrMut(s)
else:
return Error("Str! can't be other than str")
def clear(self):
self = ""
def pop(self):
if len(self) > 0:
last = self[-1]
self = self[:-1]
return last
else:
return Error("Can't pop from empty `Str!`")
def push(self, c: str):
self += c
def remove(self, idx: int):
char = self[idx]
self = self[:idx] + self[idx+1:]
return char
def insert(self, idx: int, c: str):
self = self[:idx] + c + self[idx:]