Union Types and Option Types (2025) tibleiz.net · 19 points · 6 comments · HN th...

@best

Union Types and Option Types (2025) tibleiz.net · 19 points · 6 comments · HN thread

TL;DR Author Tibleiz describes experimenting with union types in his low-level language Copper, then narrowing the feature to option types (T|Nothing). He covers the design: nil is a reserved value of the underlying type rather than a tag, the 'as' refinement operator, early-return syntax, and why he dropped compiler-inferred nil checks. He concludes that option types are worth keeping despite added complexity.

  • Copper's earlier union types were restricted: no nested unions, order-significant (T1|T2 differs from T2|T1), and no compatibility between unions, which made the compiler too complex.
  • An option type T? is T plus a nil value; nil is a reserved value per type (address 0 for pointers, -1 for a signed index, 0x8000_0000 for a spare bit in RGB colors), so no tag is stored.
  • The 'expr as id' operator binds a non-nil value to an immutable local, scoped to if blocks, while loops, and the right side of 'and'; 'or else' supports early returns.
  • The author rejected compiler-inferred nil checks (TypeScript/Kotlin style) because they needed two-pass loop analysis, interacted badly with generics, and were hard to predict in edge cases.
  • He keeps a notNil cast-like method that checks only in debug builds, and says porting the self-hosted compiler and his decompiler exposed a few bugs.

Discussion The thread is small and mostly informational. One commenter asks for a cross-language reference on language features like optional and union types, and another points to Rosetta Code's Maybe monad page. A second commenter shares a low-level tagged-union trick: putting the tag at the end so a pointer to the union is also a pointer to its value. Gnabgib links to a prior Copper discussion on Hacker News. The mood is light, with one joke about the title's 'Onion Types' typo.

  • Cross-language references for language features are useful (a few): One commenter asks where to find comparisons of how languages implement optional and union types, and a reply suggests Rosetta Code's Maybe monad examples as a practical starting point.
  • Tag placement at the end simplifies tagged unions (a few): A commenter notes that putting the discriminator after the value means a pointer to the union also points directly to the value, avoiding pointer arithmetic after discrimination in low-level code.
  • Related prior discussion of Copper exists (a few): A commenter points out that Copper was posted to Hacker News three days earlier with a larger thread of 120 comments, which may be worth reading for more context on the language.

Links from the comments

#optionTypes #unionTypes #CopperLang #programmingLanguages #nullSafety #compilers