Files
sakurac/tests/programs/array_and_generic_bounds_give_shapes_1.sakura
2026-11-19 04:54:17 -06:00

27 lines
1.4 KiB
Plaintext

import std::io;
# Within a generic's own body, a type parameter bounded by `array` is a
# `T::element[T::length]`, indexed, walked, and converted as one, with a zero
# value where it is also `zeroable`; and one `T is vector` holds of is a
# `vector<T::args...[0]>`, with `vector`'s members.
def first<T>(x: &T): T::element where T: array { return x[0]; }
def copied<T>(x: T): T::element[T::length] where T: array { return x; }
def blank<T>(): T where T: array, zeroable { var made: T::element[T::length]; var e: T::element; made[0] = e; return made; }
def count<T>(x: &T): u64 where T: array { var n: u64 = 0; for e in x { n++; } return n * 100 + x.length; }
def set_first<T>(x: &mut T, v: T::element): void where T: array { x[0] = v; }
def length_of<T>(x: &T): u64 { if const T is vector { return x.length; } return 0; }
def grow<T>(x: &mut T): void { if const T is vector { val e := x[0]; x.append(e); } }
def arm_length<T>(x: &T): u64 { return match const T { vector => x.length, array => x.length * 10, else => 0u }; }
def main(): void {
var arr: i32[3] = [7, 8, 9];
set_first(&mut arr, 70);
val made: u8[4] = blank::<u8[4]>();
println($"{first(&arr)} {copied(arr)[2]} {made.length} {made[0]} {count(&arr)}");
var v := vector::<u8>::new();
v.append(3);
grow(&mut v);
val plain: i64 = 5;
println($"{length_of(&v)} {length_of(&arr)} {arm_length(&v)} {arm_length(&arr)} {arm_length(&made)} {arm_length(&plain)}");
}