Bug 6840 – std.conv.maybeTo

Status
RESOLVED
Resolution
WORKSFORME
Severity
enhancement
Priority
P2
Component
phobos
Product
D
Version
D2
Platform
All
OS
All
Creation time
2011-10-22T13:20:00Z
Last change time
2017-07-21T04:22:32Z
Keywords
bootcamp
Assigned to
nobody
Creator
bearophile_hugs
See also
https://issues.dlang.org/show_bug.cgi?id=6843

Comments

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
Comment #2 by peter.alexander.au — 2013-12-24T02:35:29Z
*** Issue 11807 has been marked as a duplicate of this issue. ***
Comment #3 by dlang-bugzilla — 2017-07-02T00:08:57Z
I think std.conv.parse satisfies the listed advantages of the proposal today.