Regarding Nullables

Meta via Digitalmars-d digitalmars-d at puremagic.com
Sat Sep 13 09:15:50 PDT 2014


On Saturday, 13 September 2014 at 15:36:30 UTC, bearophile wrote:
> This is a little Haskell program that uses the Maybe type 
> constructor:
>
>
> foo :: Int -> Maybe Int
> foo x | x < 10 = Just x
> foo _          = Nothing
>
> main = do
>     print $ foo 5
>     print $ foo 15
>
>
> Its output:
>
> Just 5
> Nothing
>
>
>
>
> This is a similar D program, that uses Nullable:
>
> import std.stdio, std.typecons;
>
> Nullable!int foo(int x) {
>     return (x < 10) ?
>            typeof(return)(x) :
>            typeof(return)();
> }
>
> void main() {
>     writeln(foo(5));
>     writeln(foo(15));
> }
>
>
> Its output:
>
> 5
> core.exception.AssertError at C:\dmd2\src\phobos\std\typecons.d(1515): 
> Called `get' on null Nullable!int.
> ...
>
>
> I think it's better for write(Nullable!int()) to not raise an 
> error, but to print something like a "<null>" etc.
>
> A bigger problem is in the usage of Nullable. I'd like the D 
> type system to be modified and improved to support Nullables 
> with a nicer syntax.
>
> Bye,
> bearophile

I think Nullable should be completely replaced with an Option!T 
type that is also a range, and one that also doesn't `alias this` 
itself to its store. Then the above code would just print "[]" 
for an empty range. I'm sure you remember this thread: 
http://forum.dlang.org/thread/l87ivq$263r$1@digitalmars.com

The problem is that Nullable internally has a `get` function that 
checks if it is "null", and throw an error if so. It then does 
`alias get this`, which means that in some contexts, operations 
will be forwarded to `get`, and I guess one of those contexts is 
when passing the Nullable to writeln. I've run into this problem 
before, and I *thought* it had been fixed, but I guess not.


More information about the Digitalmars-d mailing list