[Issue 13017] New: opEquals for null std.typecons.Nullable
    via Digitalmars-d-bugs 
    digitalmars-d-bugs at puremagic.com
       
    Wed Jul  2 03:34:11 PDT 2014
    
    
  
https://issues.dlang.org/show_bug.cgi?id=13017
          Issue ID: 13017
           Summary: opEquals for null std.typecons.Nullable
           Product: D
           Version: D2
          Hardware: All
                OS: All
            Status: NEW
          Severity: enhancement
          Priority: P1
         Component: Phobos
          Assignee: nobody at puremagic.com
          Reporter: bearophile_hugs at eml.cc
This is a little Haskell program:
import Data.Maybe
f::Int -> Maybe Int
f 0 = Nothing
f x = Just x
main = do
    let a = f 0
    let b = f 0
    let c = f 10
    let d = f 10
    let e = f 20
    print $ a == b
    print $ a == c
    print $ c == d
    print $ d == e
Output:
True
False
True
False
This is a similar D program:
import std.stdio, std.typecons;
Nullable!int f(in int x) pure nothrow @safe @nogc {
    return (x == 0) ? typeof(return)() : typeof(return)(x);
}
void main() {
    immutable a = f(0);
    immutable b = f(0);
    immutable c = f(10);
    immutable d = f(10);
    immutable e = f(20);
    writeln(a == b);
    writeln(a == c);
    writeln(c == d);
    writeln(d == e);
}
But it raises an exception:
core.exception.AssertError at ...\dmd2\src\phobos\std\typecons.d(1361): Called
`get' on null Nullable!int.
I think here std.typecons.Nullable should act as the Haskell Maybe, and not
raise exceptions in that D program.
This means I'd like:
Nullable!int() == Nullable!int()    ===> true
Nullable!int(5) == Nullable!int()   ===> false
Nullable!int() == Nullable!int(5)   ===> false
Nullable!int(5) == Nullable!int(5)  ===> true
Nullable!int(5) == Nullable!int(10) ===> false
This is quite handy because allows to compare two nullables avoiding code like:
if ((a.isNull && b.isNull) || a == b) {
Replacing it with a more natural and equally safe (as in Haskell):
if (a == b) {
--
    
    
More information about the Digitalmars-d-bugs
mailing list