www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.bugs - [Issue 6840] New: std.conv.maybeTo

reply d-bugmail puremagic.com writes:
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



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: -------
Oct 22 2011
parent d-bugmail puremagic.com writes:
http://d.puremagic.com/issues/show_bug.cgi?id=6840




See also:


-- 
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------
Jul 27 2013