From 700b7b96f8244bdd6f69fd9129efdd1bba504b55 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominik=20Inf=C3=BChr?= Date: Fri, 7 Feb 2025 14:01:39 +0100 Subject: [PATCH] tests: Prepare (ignored) test for enumerate() method --- pkgs/std/traits.dora | 24 ++++++++++++++++++++++++ tests/stdlib/iterator-enumerate.dora | 22 ++++++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 tests/stdlib/iterator-enumerate.dora diff --git a/pkgs/std/traits.dora b/pkgs/std/traits.dora index a1500ca96..f2f0807f4 100644 --- a/pkgs/std/traits.dora +++ b/pkgs/std/traits.dora @@ -154,6 +154,11 @@ pub trait Iterator { result } + + @TraitObjectIgnore + fn enumerate(): Enumerate[Self] { + Enumerate[Self](it = self, idx = 0) + } } pub trait IntoIterator { @@ -161,6 +166,25 @@ pub trait IntoIterator { fn iter(): Self::IteratorType; } +pub class Enumerate[I: Iterator] { + it: I, + idx: Int, +} + +impl[I: Iterator] Iterator for Enumerate[I] { + type Item = (Int, I::Item); + + fn next(): Option[(Int, I::Item)] { + if self.it.next() is Some(value) { + let idx = self.idx; + self.idx += 1; + Some[(Int, I::Item)]((idx, value)) + } else { + None[(Int, I::Item)] + } + } +} + pub trait IndexGet { type Index; type Item; diff --git a/tests/stdlib/iterator-enumerate.dora b/tests/stdlib/iterator-enumerate.dora new file mode 100644 index 000000000..c90d092be --- /dev/null +++ b/tests/stdlib/iterator-enumerate.dora @@ -0,0 +1,22 @@ +//= ignore + +use std::collections::{HashMap, VecIter}; +use std::traits::Enumerate; + +fn main() { + let x = Vec[Int]::new(1, 2, 3, 4, 5); + let it1: VecIter[Int] = x.iter(); + let it: Enumerate[VecIter[Int]] = it1.enumerate(); + assert(Some[(Int, Int)]((0, 1)) == it.next()); + assert(Some[(Int, Int)]((1, 2)) == it.next()); + assert(Some[(Int, Int)]((2, 3)) == it.next()); + assert(Some[(Int, Int)]((3, 4)) == it.next()); + assert(Some[(Int, Int)]((4, 5)) == it.next()); + assert(it.next() is None); + + // let x = Array[Int]::new(1, 2, 3, 4, 5); + // assert(x.iter().count() == 5); + + // let x = HashMap[Int, String]::new((1, "one"), (2, "two"), (3, "three")); + // assert(x.iter().count() == 3); +}