import std::io; trait Show { def show(this: &Show): string; } struct point: Show { var x: int; var y: int; } def point::show(this: &point): string { return $"({this.x}, {this.y})"; } struct box: Show where T: Show { var value: T; } def box::show(this: &box): string { return $"[{this.value.show()}]"; } def describe(item: &Show): string { return item.show(); } def show_all(xs: span): string where T: Show { var out := string::new(nothing {}); for x in xs { out.append($"{x.show()}{describe(&x)} "); } return out; } union res { var value: T; var failure: span; } def res::ok(value: T): res { return res::{ value = value }; } def res::or(this: &res, fallback: T): T { match this { value(value) => return value; else => return fallback; } } struct pair { var first: A; var second: B; } def pair::swap(this: &pair): pair { return pair::{ this.second, this.first }; } def map(xs: span, out: *mut U, f: def(T): U): span { for i in 0..xs.length { out[i] = f(xs[i]); } return span::::over(out as *U, xs.length); } def fold(xs: span, start: A, f: def(A, T): A): A { var acc := start; for x in xs { acc = f(acc, x); } return acc; } def max(a: T, b: T): T where T: ordered { return a > b ? a : b; } def sum(xs: span): T where T: numeric { var total: T = 0; for x in xs { total += x; } return total; } struct node { var value: T; var next: *node; } def node::length(this: &node): int { return this.next == null ? 1 : 1 + (*this.next).length(); } def main(): void { val p := point{ 1, 2 }; val b := box{ value = p }; var ps: point[1] = [p]; var bs: box[1] = [b]; print($"{show_all(span::::over((&ps) as *point, 1))}{describe(&b)} {show_all(span::>::over((&bs) as *box, 1))}"); val r := res::::ok(3); val e := res::{ failure = "no" }; print($"{r.or(0)} {e.or(-1)} "); val q := pair::>{ first = 1, second = "one" }; val nested: pair>, int> = pair{ q, 2 }; print($"{q.swap()} {nested.first.second} "); var ns: int[2] = [1, 2]; var tripled: int[2]; var fs: f64[2] = [1.5, 2.5]; print($"{map(span::::over((&ns) as *int, 2), (&mut tripled) as *mut int, def(n) => n * 3)} {fold(span::::over((&fs) as *f64, 2), 0.0, def(a, x) => a + x)} "); var threes: int[3] = [1, 2, 3]; var halves: f64[2] = [0.5, 0.25]; print($"{max(3, 7)} {max::(250, 9)} {sum(span::::over((&threes) as *int, 3))} {sum(span::::over((&halves) as *f64, 2))} "); val last := node{ 3, null }; val first := node{ 1, &last as *node }; val biggest := max::; println($"{first.length()} {biggest(0.5, 1.5)}"); }