57 lines
1.4 KiB
Plaintext
57 lines
1.4 KiB
Plaintext
import std::io;
|
|
|
|
# A pattern parameter of a fixed array, `L[N]`, is given an array type and names
|
|
# its element's type and its length, so `lanes<f32[4]>` is four `f32`s, generic
|
|
# code is written over `L` and `N`, and inference reads them from arguments.
|
|
|
|
struct lanes<L[N]> where L: numeric, zeroable {
|
|
var items: L[N];
|
|
}
|
|
|
|
def lanes<L[N]>::count(&this): u64 {
|
|
return N;
|
|
}
|
|
|
|
def lanes<L[N]>::sum(&this): L {
|
|
var total: L;
|
|
for i in 0..N {
|
|
total = total + this.items[i];
|
|
}
|
|
return total;
|
|
}
|
|
|
|
def lanes<L[N]>::add(&this, other: &lanes<L[N]>): lanes<L[N]> {
|
|
var made: lanes<L[N]>;
|
|
for i in 0..N {
|
|
made.items[i] = this.items[i] + other.items[i];
|
|
}
|
|
return made;
|
|
}
|
|
|
|
def first<L, const N: u64>(v: &lanes<L[N]>): L where L: numeric, zeroable {
|
|
return v.items[0];
|
|
}
|
|
|
|
# An array of arrays is given whole: its element is an array.
|
|
struct rows<R[N]> { var items: R[N]; }
|
|
|
|
def rows<R[N]>::count(&this): u64 {
|
|
return N;
|
|
}
|
|
|
|
type four = lanes<f32[4]>;
|
|
type grid = rows<lanes<u8[2]>[3]>;
|
|
|
|
def main(): void {
|
|
val a := lanes::<f32[4]> { items = [1.0, 2.0, 3.0, 4.5] };
|
|
val b: four = four { items = [10.0, 20.0, 30.0, 40.0] };
|
|
val c := a + b;
|
|
io::println($"{c.count()} {c.sum()} {first(&c)}");
|
|
val d := lanes::<u8[16]> {};
|
|
io::println($"{d.count()} {d.sum()}");
|
|
val e := lanes::<i64[2]> { items = [5, -7] };
|
|
io::println($"{e.sum()}");
|
|
val g := grid {};
|
|
io::println($"{g.count()} {g.items[0].count()}");
|
|
}
|