Files
sakurac/tests/programs/loops_walk_iterators_1.sakura
T

32 lines
2.0 KiB
Plaintext
Raw Normal View History

2026-10-26 10:14:11 -05:00
import std::io;
struct bag { var items: i64[4]; var count: u64; }
struct bag::reader : iter<&i64> { val of: *i64; var at: u64; val count: u64; }
def bag::reader::next(&mut this): maybe<&i64> { if this.at >= this.count { return nothing {}; } this.at++; return &this.of[this.at - 1]; }
struct bag::writer : iter<&mut i64> { val of: *mut i64; var at: u64; val count: u64; }
def bag::writer::next(&mut this): maybe<&mut i64> { if this.at >= this.count { return nothing {}; } this.at++; return &mut this.of[this.at - 1]; }
type bag::iterator = bag::reader;
type bag::mutator = bag::writer;
def bag::iter(&this): bag::reader { return bag::reader{ of = (&this.items) as *i64, at = 0, count = this.count }; }
def bag::iter(&mut this): bag::writer { return bag::writer{ of = (&mut this.items) as *mut i64, at = 0, count = this.count }; }
struct countdown : iter<i64>, owning { var n: i64; }
def countdown::next(&mut this): maybe<i64> { if this.n == 0 { return nothing {}; } this.n--; return this.n + 1; }
def countdown::close(&mut this): void { print($"closed at {this.n} "); }
struct upto : iter<i64> { var n: i64; val to: i64; }
def upto::next(&mut this): maybe<i64> { if this.n >= this.to { return nothing {}; } this.n++; return this.n; }
const def total(to: i64): i64 { var t: i64 = 0; for x in (upto{ n = 0, to = to }) { t += x; } return t; }
const TEN := total(4);
def sum<C>(c: &C): i64 where C: iterable<i64> { var t: i64 = 0; for x in c { t += x; } return t; }
def first_under(limit: i64): i64 { for n in (countdown{ n = 6 }) { if n < limit { return n; } } return -1; }
def main(): void {
var b := bag{ items = [1, 2, 3, 4], count = 3 };
for x in b { print($"{x} "); }
for &mut x in b { x *= 10; }
for i, &x in b { print($"{i}:{x} "); }
print($"sum {sum(&b)} ");
for n in (countdown{ n = 5 }) { if n == 3 { break; } print($"{n} "); }
var it := countdown{ n = 4 };
for n in it { if n == 2 { break; } }
for n in it { print($"rest {n} "); }
print($"first {first_under(4)} ");
println($"{TEN}");
}