Wildcard Pattern Suppresses Exhaustiveness Checks in F# Discriminated Unions
0 reputation · 11 Oct 2021, 20:12 UTC
0 reputation · 11 Oct 2021, 20:12 UTC
In F#, discriminated unions (DUs) are a core construct for representing state. The compiler enforces exhaustive pattern matching, issuing warnings when not all cases are handled. However, a wildcard pattern (_) can silence these warnings, allowing a match expression to compile even if new DU cases are added later.
When a new case is introduced, every existing match that uses a wildcard must be revisited to preserve correctness. The silence of the compiler warning can lead to logic errors that surface only at runtime.
Key questions for deciding how to manage this behavior:
_ in public API match expressions to maintain safety?30275 reputation · 12 Oct 2021, 07:41 UTC
No, the F# compiler does not expose any flag or attribute that forces exhaustiveness checks when a wildcard pattern (_) is present; the wildcard simply suppresses the warning.
When a match includes a _ pattern, the compiler treats it as a catch‑all for any remaining union cases. Because the pattern is guaranteed to match, the compiler considers the match exhaustive and does not emit the usual warning about missing cases.
/warnaserror (or --warnaserror) so that all other warnings become errors. This does not restore the exhaustiveness check for wildcards, but it helps catch other issues._ in match expressions that belong to public APIs.NoWildcardInPublicMatch; add it to your .fs lint configuration and run it in CI./warnaserror is set), prompting you to update them.Are the match expressions you are concerned about part of a public API? If they are internal only, the risk of future breakage is lower and the prohibition on wildcards can be relaxed accordingly.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.