Files
sakurac/tests/programs/ranges_are_values_1.sakura
T
2026-10-28 22:13:49 -05:00

39 lines
1.2 KiB
Plaintext

import std::io;
# A range is a value of std's `range<T>`: kept, passed, and walked later.
def total(r: range<u64>): u64 {
var t: u64 = 0;
for x in r { t += x; }
return t;
}
def main(): void {
val r := 2..6;
val inclusive: range<u8> = 1..=4;
print($"{r.remaining()} {inclusive.remaining()} {r.contains(5)} {r.contains(6)} ");
print($"{total(1..=10)} {total(0..0)} ");
# `..=` reaches the type's last value without wrapping past it.
var top: u64 = 0;
for b in (250 as u8)..=255 { top += b as u64; }
print($"{top} ");
for i in 0..=3 { print($"{i}"); }
print(" ");
# A loop over a range counts where it is, so walking it from both ends meets in
# the middle.
var both := 0..7;
while both.next() is some(front) {
print($"{front}");
if both.next_back() is some(back) { print($"{back}"); }
}
print(" ");
for i in (1..=9).rev().step(3) { print($"{i}"); }
print(" ");
for i in (0..20).step(5) { print($"{i},"); }
print(" ");
val empty := 5..2;
print($"{empty.is_empty()} {empty.remaining()} ");
var counted := 10..=12;
print($"{counted.nth(1) else 0} {counted.count()} ");
println($"{(1..=5).sum()} {(1..=5).product()}");
}