diff --git a/pkgs/std/collections.dora b/pkgs/std/collections.dora index ac5594501..d9aa4615d 100644 --- a/pkgs/std/collections.dora +++ b/pkgs/std/collections.dora @@ -82,6 +82,22 @@ impl[T: Zero] Array[T] { } } +impl[T: Stringable] Array[T] { + pub fn join(separator: String): String { + let output = StringBuffer::new(); + + for (idx, element) in self.enumerate() { + if idx > 0 { + output.append(separator); + } + + output.append(element.toString()); + } + + output.toString() + } +} + impl[T] IntoIterator for Array[T] { type IteratorType = ArrayIter[T]; @@ -1407,6 +1423,20 @@ impl[T: Stringable] Vec[T] { sb.append(")"); return sb.toString(); } + + pub fn join(separator: String): String { + let output = StringBuffer::new(); + + for (idx, element) in self.enumerate() { + if idx > 0 { + output.append(separator); + } + + output.append(element.toString()); + } + + output.toString() + } } impl[T1: Equals, T2: Equals] Equals for (T1, T2) { diff --git a/tests/stdlib/array-join1.dora b/tests/stdlib/array-join1.dora new file mode 100644 index 000000000..92d18b7a8 --- /dev/null +++ b/tests/stdlib/array-join1.dora @@ -0,0 +1,13 @@ +fn main() { + let x = Array[Int64]::new(1, 2, 3); + assert(x.join(", ") == "1, 2, 3"); + assert(x.join("-") == "1-2-3"); + + let x = Array[Char]::new('a', 'b', 'c'); + assert(x.join(", ") == "a, b, c"); + assert(x.join("-") == "a-b-c"); + + let x = Array[Int64]::new(101, 102, 103); + assert(x.join(", ") == "101, 102, 103"); + assert(x.join("-") == "101-102-103"); +} diff --git a/tests/stdlib/vec-join1.dora b/tests/stdlib/vec-join1.dora new file mode 100644 index 000000000..a754fc54e --- /dev/null +++ b/tests/stdlib/vec-join1.dora @@ -0,0 +1,13 @@ +fn main() { + let x = Vec[Int64]::new(1, 2, 3); + assert(x.join(", ") == "1, 2, 3"); + assert(x.join("-") == "1-2-3"); + + let x = Vec[Char]::new('a', 'b', 'c'); + assert(x.join(", ") == "a, b, c"); + assert(x.join("-") == "a-b-c"); + + let x = Vec[Int64]::new(101, 102, 103); + assert(x.join(", ") == "101, 102, 103"); + assert(x.join("-") == "101-102-103"); +}