Comment #0 by bearophile_hugs — 2011-10-22T13:20:49Z
This simple idea comes from usage of some Haskell. I think in Phobos (probably in std.conv) it's useful to have a function template that works like this maybeTo:
import std.stdio, std.typecons, std.conv;
template maybeTo(Tout) {
Nullable!Tout maybeTo(Tin)(Tin x) nothrow /*pure*/ {
typeof(return) result;
try {
result = to!Tout(x);
} catch (ConvException e) {
} catch (Throwable e) {
assert(0, "Not supposed to happen.");
}
return result;
}
}
void main() nothrow {
auto mx1 = maybeTo!int("12");
assert(!mx1.isNull && mx1 == 12);
//writeln(mx1); // Nullable!(int)(12, false)
auto mx2 = maybeTo!int("12a");
assert(mx2.isNull);
//writeln(mx2); // Nullable!(int)(0, true)
}
Notes:
1) This maybeTo code is not meant to be its final implementation, it's here mostly to show its intended semantics.
2) maybeTo is not meant to replace to!(), it is meant to be just an alternative.
Advantages of maybeTo:
1) It's usable in nothrow functions too. Maybe it will be usable in pure functions too.
2) This simple implementation of maybeTo contains a try-catch, but there is no need to actually throw and catch an exception in all wrong conversion cases. Example: when Tin is string and Tout is int, maybeTo is free to use something lighter, like a C function that produces no exceptions, instead of to!(). I think this allows the compiler to perform some extra optimizations.
Alternative name: "nullableTo". But I like the name "Maybe", as in Haskell.
Comment #1 by bearophile_hugs — 2013-07-27T09:43:19Z