Comment by cowlevel
1 day ago
In general it's a problem of sentinel values. Some languages let you abstract this - I think in Rust and C++ you can define an "intrusive optional" which is like optional but uses an invalid value pattern to store the not-present state. In memory it's the same as a sentinel value but the compiler forces you to unwrap it like an optional.
I'm not sure how well the 'forcing' works for Rust and C++. You can definitely do this kind of thing in dependently typed languages.
The type is akin to optional<int>. You can't add 5 to it, you have to dereference it first which crashes if it was null (0 or another chosen value).
Well, in Rust you would use pattern matching, which can't even crash.
In Haskell, the closest thing to adding 5 to an optional value would be something like:
This one leaves 'Nothing' alone, but adds 5 in case the value is present.