41 lines
1.7 KiB
Plaintext
41 lines
1.7 KiB
Plaintext
import std::io;
|
|
trait Into<T> {
|
|
def into(&this): T;
|
|
def twice(&this): T[2] { return [this.into(), this.into()]; }
|
|
}
|
|
trait Map<K, V> { def get(&this, key: K): V; }
|
|
struct counted { var it: &Into<int>; }
|
|
struct meters: Into<span<u8>> { var v: f64; }
|
|
def meters::into(&this): span<u8> { return this.v < 3.0 ? "2m" : "far"; }
|
|
struct count { var n: int; }
|
|
def count::into(&this): int { return this.n * 10; }
|
|
struct box<T> { var value: T; }
|
|
def box<T>::into(&this): T { return this.value; }
|
|
struct table { var keys: span<span<u8>>; var values: span<int>; }
|
|
def table::get(&this, key: span<u8>): int {
|
|
for i in 0..this.keys.length { if this.keys[i] == key { return this.values[i]; } }
|
|
return -1;
|
|
}
|
|
def show(x: &Into<span<u8>>): span<u8> { return x.into(); }
|
|
def total(xs: span<counted>): int { var t := 0; for x in xs { t += x.it.into(); } return t; }
|
|
def pick<T>(x: &Into<T>): T { return x.into(); }
|
|
def convert<T, U>(x: &T): U where T: Into<U> { return x.into(); }
|
|
def lookup<K, V>(m: &Map<K, V>, key: K): V { return m.get(key); }
|
|
def main(): void {
|
|
val m := meters{ 2 };
|
|
println($"{show(m)} {m.twice()} {convert::<meters, span<u8>>(m)}");
|
|
val c := count{ 3 };
|
|
val b := box{ 4 };
|
|
val more := box{ 5 };
|
|
var parts: counted[3] = [counted{ &c }, counted{ &b }, counted{ &more }];
|
|
val held := span::<counted>::over((&parts) as *counted, 3);
|
|
val word := box::<span<u8>>{ "s" };
|
|
println($"{total(held)} {pick(c)} {pick(word)} {parts[1].it.twice()} {parts[0].it.twice()}");
|
|
val keys: span<u8>[2] = ["a", "b"];
|
|
val values: int[2] = [1, 2];
|
|
val t := table{ span::<span<u8>>::over((&keys) as *span<u8>, 2),
|
|
span::<int>::over((&values) as *int, 2) };
|
|
val key := "b";
|
|
println($"{lookup(t, key)} {(&t as &Map<span<u8>, int>).get(key)}");
|
|
}
|