import std::io; # The branch a ternary takes where its condition holds ends at `:`, so it may be a # fallback, `ok ? parse(text) else 0 : 1`, which is only worked out where that # branch is taken. An owning value the union of a result holds is named with # `is value(&p)`, then copied or moved by name. struct flags { var build: bool; } struct job { var flags: flags; var system: strview; } # A path is written with its system's delimiter, `\` on Windows, so each is shown # with `/` to read the same on every system. def shown(text: strview): string { var made := string::new(nothing {}); for byte in text { made.push(byte == path_delim ? '/' : byte); } return made; } def named(asked: &job, given: strview): string { val outpath := path::parse(given); if outpath is not value(&p) { return string::from("bad", nothing {}); } val final := asked.flags.build && asked.system == "windows" ? p.with_extension("exe") else copy(p) : copy(p); return shown(final.view()); } def moved(asked: &job, given: strview): string { var outpath := path::parse(given); if outpath is not value(&mut p) { return string::from("bad", nothing {}); } val final := asked.flags.build && asked.system == "windows" ? p.with_extension("exe") else move(p) : move(p); return string::from($"{shown(final.view())} [{shown(p.view())}]", nothing {}); } def half(n: i64): maybe { return nothing {} if n % 2 != 0; return n / 2; } def halve(n: i64): result { return "odd" if n % 2 != 0; return n / 2; } var calls: i64 = 0; def counted(n: i64): maybe { calls++; return half(n); } def fallen(): i64 { calls += 100; return -1; } const known: i64 = true ? half(10) else 0 : 99; const unknown: i64 = true ? half(7) else -7 : 99; def main(): void { val win := job { flags = flags { build = true }, system = "windows" }; val lin := job { flags = flags { build = true }, system = "linux" }; for &each in ["out/prog", "out/prog.o", "out/"] { println($"{named(&win, each)} | {named(&lin, each)} | {moved(&win, each)} | {moved(&lin, each)}"); } for n in 0..4 { val a := n > 1 ? half(n) else 100 : 200; val b := n > 1 ? halve(n) else (e) { println($"left: {e}"); continue; } : 300; val c := n > 2 ? half(n) else 1 : n > 0 ? half(n + 1) else 2 : 3; val d := n > 1 ? half(n) else 4 : (half(n) else 5); println($"{n}: {a} {b} {c} {d}"); } calls = 0; val e := false ? counted(4) else fallen() : 7; val f := true ? counted(4) else fallen() : 7; val g := true ? counted(5) else fallen() : 7; println($"{e} {f} {g} calls {calls}"); if (true ? half(3) else 0 : 1) == 0 { println("zero"); } println($"{known} {unknown}"); }