draft proposal for Sum Types for D

Andy andy.pj.hanson at gmail.com
Fri Dec 2 06:54:14 UTC 2022


I would suggest implementing option types in the language instead 
of requiring the user to define them using a sumtype. (You might 
lower them to a sumtype though.) First of all because writing 
`T?` is more convenient than writing a sumtype.

If option types are first-class, you could include a syntax for 
unwrapping the option. Compare:

	// someFunc() is an `int?`, x is an `int`
	if (auto x ?= someFunc()) { use(x); }

Vs:

	auto option = someFunc();
	if (?option.value) { use(option.value); }

With the latter syntax I would probably want to define `auto x = 
option.value;` anyway if I were using it multiple times.

You could also use an option as the value for `s.x` where `s` is 
a sumtype and `x` is a member; that way it can't possibly fail 
and there's no need for two separate operations to query and get 
it. Then use `if (auto x ?= s.x)` to access it with no possible 
runtime error. That's better than having to check a boolean 
`?s.x` and then access it later, which is exactly the kind of API 
I would expect from a language without options.


More information about the Digitalmars-d mailing list