Bug 13017 – opEquals for null std.typecons.Nullable
Status
RESOLVED
Resolution
FIXED
Severity
enhancement
Priority
P1
Component
phobos
Product
D
Version
D2
Platform
All
OS
All
Creation time
2014-07-02T10:34:00Z
Last change time
2017-05-02T07:29:47Z
Assigned to
nobody
Creator
bearophile_hugs
Comments
Comment #0 by bearophile_hugs — 2014-07-02T10:34:11Z
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@...\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) {
Comment #1 by chalucha — 2015-09-04T08:35:40Z
Similar problem, same exception:
import std.typecons;
struct Foo
{
Nullable!int field;
}
void main()
{
Foo a;
assert (a == Foo.init);
}
Comment #2 by jack — 2016-04-05T00:13:29Z
*** Issue 14804 has been marked as a duplicate of this issue. ***
Comment #3 by luis — 2016-04-05T18:14:36Z
This is the behavior I was looking for / expecting, unlike the behavior suggested in Issue 14804, which would be more akin to NaNs (nulls don't compare equal).
Comment #4 by issues.dlang — 2017-01-13T04:09:37Z
Blast it. The current behavior is _extremely_ annoying once you start having member variables which are Nullable. You're forced to implement opEquals to work around this.