From 9ac8248609da5d0bbcf7ccfaf63325a0a44c6b39 Mon Sep 17 00:00:00 2001 From: Shunsuke Shibayama Date: Sun, 27 Nov 2022 16:35:50 +0900 Subject: [PATCH] Implement some primitive types methods --- compiler/erg_compiler/lib/std/_erg_array.py | 4 +++ compiler/erg_compiler/lib/std/_erg_nat.py | 6 +++++ compiler/erg_compiler/lib/std/_erg_str.py | 29 +++++++++++++++++++++ 3 files changed, 39 insertions(+) diff --git a/compiler/erg_compiler/lib/std/_erg_array.py b/compiler/erg_compiler/lib/std/_erg_array.py index 2d5af648..43c6f1c4 100644 --- a/compiler/erg_compiler/lib/std/_erg_array.py +++ b/compiler/erg_compiler/lib/std/_erg_array.py @@ -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 diff --git a/compiler/erg_compiler/lib/std/_erg_nat.py b/compiler/erg_compiler/lib/std/_erg_nat.py index d47c36b0..dbaefc4e 100644 --- a/compiler/erg_compiler/lib/std/_erg_nat.py +++ b/compiler/erg_compiler/lib/std/_erg_nat.py @@ -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 diff --git a/compiler/erg_compiler/lib/std/_erg_str.py b/compiler/erg_compiler/lib/std/_erg_str.py index 74b76039..6d278376 100644 --- a/compiler/erg_compiler/lib/std/_erg_str.py +++ b/compiler/erg_compiler/lib/std/_erg_str.py @@ -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:]