Skip to content

Commit

Permalink
tests: Prepare (ignored) test for enumerate() method
Browse files Browse the repository at this point in the history
  • Loading branch information
dinfuehr committed Feb 7, 2025
1 parent fa38f35 commit 700b7b9
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 0 deletions.
24 changes: 24 additions & 0 deletions pkgs/std/traits.dora
Original file line number Diff line number Diff line change
Expand Up @@ -154,13 +154,37 @@ pub trait Iterator {

result
}

@TraitObjectIgnore
fn enumerate(): Enumerate[Self] {
Enumerate[Self](it = self, idx = 0)
}
}

pub trait IntoIterator {
type IteratorType: Iterator;
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;
Expand Down
22 changes: 22 additions & 0 deletions tests/stdlib/iterator-enumerate.dora
Original file line number Diff line number Diff line change
@@ -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);
}

0 comments on commit 700b7b9

Please sign in to comment.