Idiomatic way to express errors without resorting to exceptions

Paul Backus snarwin at gmail.com
Sat Feb 29 15:09:54 UTC 2020


On Saturday, 29 February 2020 at 13:40:11 UTC, Adnan wrote:
> On Saturday, 29 February 2020 at 13:03:21 UTC, Sebastiaan Koppe 
> wrote:
>> On Saturday, 29 February 2020 at 12:50:59 UTC, Adnan wrote:
>>> * Option!T from the optional package: Has even worse problem 
>>> IMO. Not only it allows None + int but also it returns a 
>>> `[]`. This API is not to my liking. You could say well 
>>> Haskell has fmap for Optional etc, and I am aware of that, so 
>>> does Rust with map etc. But I am talking about basic things: 
>>> like `+`.
>>
>> I would argue it is one of its strengths.
>
> Doesn't that pretty much defeat the entire purpose of 
> type-guarding a potentially error/absent value?

I suppose it depends on what you think that purpose is.

Optional!T will not allow you to do anything that requires a T 
unless the T is actually present. In some cases, it will allow 
you to *attempt* such operations, and return an empty Optional at 
run time if they are not allowed; in others, the attempt will 
result in a type error at compile time. This is a compromise 
between strictness and convenience, but there is no compromise to 
correctness. Unlike, say, a null pointer, Optional!T will not 
allow you to cause a run-time error by forgetting a check.

(Of course, you can explicitly unwrap the Optional without 
checking, but that's not something you're likely to do by 
accident.)


More information about the Digitalmars-d-learn mailing list