October 22, 2011 [Issue 6840] New: std.conv.maybeTo | ||||
---|---|---|---|---|
| ||||
http://d.puremagic.com/issues/show_bug.cgi?id=6840 Summary: std.conv.maybeTo Product: D Version: D2 Platform: All OS/Version: All Status: NEW Severity: enhancement Priority: P2 Component: Phobos AssignedTo: nobody@puremagic.com ReportedBy: bearophile_hugs@eml.cc --- Comment #0 from bearophile_hugs@eml.cc 2011-10-22 13:20:49 PDT --- 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. -- Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email ------- You are receiving this mail because: ------- |
July 27, 2013 [Issue 6840] std.conv.maybeTo | ||||
---|---|---|---|---|
| ||||
Posted in reply to bearophile_hugs@eml.cc | http://d.puremagic.com/issues/show_bug.cgi?id=6840 --- Comment #1 from bearophile_hugs@eml.cc 2013-07-27 09:43:19 PDT --- See also: http://dlang.org/phobos/std_exception.html#.ifThrown -- Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email ------- You are receiving this mail because: ------- |
Copyright © 1999-2021 by the D Language Foundation