43 lines
1.5 KiB
Plaintext
43 lines
1.5 KiB
Plaintext
import std::io;
|
|||
|
|
|
||
|
|
# A property named as a value is its `get`, a function of `&this`, and a method
|
||
|
|
# or property of a generic type named without its type arguments takes them
|
||
|
|
# from the function type expected, or from a parameter's `invokable` bound, as
|
||
|
|
# an adapter's is.
|
||
|
|
|
||
|
|
struct rect { var w: f32; var h: f32; }
|
||
|
|
val rect::area: f32 { get => this.w * this.h; }
|
||
|
|
var rect::width: f32 { get => this.w; set => this.w = value; }
|
||
|
|
|
||
|
|
union outcome<T> { var failed: strview; var made: T; }
|
||
|
|
val outcome<T>::ok: bool { get => this is made; }
|
||
|
|
def outcome<T>::take(&this): T { return this.made; }
|
||
|
|
|
||
|
|
def read(text: &strview): outcome<i64> {
|
||
|
|
return "not a digit" if text.length != 1 || text[0] < '0' || text[0] > '9';
|
||
|
|
return (text[0] - '0') as i64;
|
||
|
|
}
|
||
|
|
|
||
|
|
def doubled<T>(xs: span<outcome<T>>): vector<T> where T: integer {
|
||
|
|
return xs.iter().copied().filter(outcome::ok).map(def(o) => o.take() * 2).to_vector();
|
||
|
|
}
|
||
|
|
|
||
|
|
def main(): void {
|
||
|
|
var r := rect { w = 3, h = 4 };
|
||
|
|
val area: def(&rect): f32 = rect::area;
|
||
|
|
val width: def(&rect): f32 = rect::width;
|
||
|
|
r.width = 5;
|
||
|
|
println($"{area(&r)} {width(&r)}");
|
||
|
|
|
||
|
|
val texts: strview[5] = ["1", "x", "7", "", "3"];
|
||
|
|
val read_all := texts[:].iter().map(read).to_vector();
|
||
|
|
val kept := read_all.span.iter().copied().filter(outcome::ok).map(def(o) => o.take()).to_vector();
|
||
|
|
println($"{kept.length}: {kept[0]} {kept[1]} {kept[2]}");
|
||
|
|
|
||
|
|
val take: def(&outcome<i64>): i64 = outcome::take;
|
||
|
|
val first: outcome<i64> = 9;
|
||
|
|
println($"{take(&first)}");
|
||
|
|
|
||
|
|
val twice := doubled(read_all.span);
|
||
|
|
println($"{twice[0]} {twice[1]} {twice[2]}");
|
||
|
|
}
|