hn.today

Union Types and Option Types

tibleiz.net50 points21 comments
Screenshot of Union Types and Option Types

Experiments with union types in Copper, a minimalist low-level language, exposed the cost of supporting arbitrary alternatives. The design used tags for general unions and a special null-pointer representation for pointer-or-nothing values, but required restrictions: unions could not be nested, alternative order mattered, and differently sized unions were incompatible. Because the main uses were optional values and errors, the author dropped general unions and focused on option types, written T? for T or nil. Each type reserves one value for nil, avoiding tags and fitting native C APIs, though some types have no suitable spare value and nested options are impossible. To use an optional safely, code can test it with “as,” which introduces a non-optional local within a limited scope; “or else” supports early returns. Unsafe refinement is also possible, with a debug-time nil check.

The author also tested compiler-inferred nil checks, like those in TypeScript or Kotlin, so ordinary nil tests automatically make later uses safe. This was concise but required complex loop analysis, behaved poorly with generic functions, and made program validity depend on which cases the checker recognized; it also added compiler overhead. The author reverted to explicit refinement. Option types clarify which values may be absent and prevent accidental nil dereferences, but add concepts to a language intended to remain simple. Porting Copper, an editor, and a complex decompiler surfaced potential and actual bugs, underscoring the tension between compiler-enforced safety and code that reflects real algorithmic guarantees without awkward workarounds.

Read on tibleiz.net21 comments on Hacker News

Summary generated by AI from the linked article. hn.today is not affiliated with Hacker News or Y Combinator.

More in Programming

The daily digest

Today's best Hacker News stories, summarized and screenshotted, one email a day.