Is there anything other than nullable to work with optional types?
aliak via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Sun Dec 25 11:22:10 PST 2016
Hey,
So, been using the programming language swift for a while now,
the optional types[1] they support makes working with maybe-type
(ala haskell) values extremely pleasant.
Does D have anything other than the Nullable template that can be
used to work with optionals, or is there a way for it to not be
so cumbersome to work with?
Eg: Currently I have a function like this:
struct MarkerData {
long start;
long end;
long length;
long times;
}
Nullable!MarkerData pluckMarker(string str) {
auto start = str.indexOf("(");
if (start == -1) {
return typeof(return).init;
}
auto end = str.indexOf(")", start);
if (end == -1) {
return typeof(return).init;
}
auto parts = str[start+1..end].split("x");
auto length = to!long(parts[0]);
auto times = to!long(parts[1]);
return Nullable!MarkerData(MarkerData(start, end, length,
times));
}
Everywhere I have to return the Nullable! type, I have to either
use that typeof(return).init to make it a null value, or a quite
verbose constructor call to return a concrete type.
Can it be made simpler to use without me having to alias
Nullable!MarkerData (which still wouldn't help with just
returning null).
[1] will try a super quick explanation of optional types. You
basically add a '?' to any type declaration and then it's
nullable. And you can implicitly assign nil and also the concrete
type.
More information about the Digitalmars-d-learn
mailing list