result
nimony/lib/std/result.nim
result — a success-or-error sum type built on Nimony's native sum types.
Result[T, E] holds exactly one of Ok (the value, type T) or Err (the error, type E).
ok(v) / err(e) infer the parameter their argument does not fix from the call's expected type, so an annotated target (a typed result, let, proc return, etc.) is enough — result = ok(8080) in a Result[int, string] context binds E = string. Spell both out (ok[int, string](v)) only where there is no expected type to infer from.
unsafeGet raises BugError on the wrong variant (a system ErrorCode — calling it unguarded is a programming error); guard with isOk, or use the total get(default).
import std/result proc parsePort(s: string): Result[int, string] = if s == "": result = err("empty") else: result = ok(8080) let r = parsePort("80") if r.isOk: echo r.get(0) else: echo r.error("?")
type Result = object case `kind: `sumtype of Ok: okVal: T of Err: errVal: E
proc ok(v: T): Result[T,E]A success
Result(theOkcase).Eis inferred from the expected type.proc err(e: E): Result[T,E]A failure
Result(theErrcase).Tis inferred from the expected type.proc isOk(r: Result[T,E]): boolproc isErr(r: Result[T,E]): boolproc get(r: Result[T,E]; default: T): Tproc error(r: Result[T,E]; default: E): Eproc unsafeGet(r: Result[T,E]): T