Issue 6840 - std.conv.maybeTo
Summary: std.conv.maybeTo
Status: RESOLVED WORKSFORME
Alias: None
Product: D
Classification: Unclassified
Component: phobos (show other issues)
Version: D2
Hardware: All All
: P2 enhancement
Assignee: No Owner
URL:
Keywords: bootcamp
: 11807 (view as issue list)
Depends on:
Blocks:
 
Reported: 2011-10-22 13:20 UTC by bearophile_hugs
Modified: 2017-07-21 04:22 UTC (History)
4 users (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description bearophile_hugs 2011-10-22 13:20:49 UTC
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 bearophile_hugs 2013-07-27 09:43:19 UTC
See also:
http://dlang.org/phobos/std_exception.html#.ifThrown
Comment 2 Peter Alexander 2013-12-24 02:35:29 UTC
*** Issue 11807 has been marked as a duplicate of this issue. ***
Comment 3 Vladimir Panteleev 2017-07-02 00:08:57 UTC
I think std.conv.parse satisfies the listed advantages of the proposal today.