Regarding Nullables

"Nordlöw" via Digitalmars-d digitalmars-d at puremagic.com
Sun Sep 14 12:49:53 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

Further I would like rules for implicit conversion to bool of a
new template Optional behave as:

- null => false
- otherwise => true

This makes pattern-matching much more natural such as

if (auto hit = context.tryMatch!T) // returns Optional!T
{
      use_hit(hit);
}
else if (auto hit = context.tryNextRule!U) // returns Optional!U
{
      use_hit(hit);
}

With D's lazy evaluation matchers can be chained. See for example
my use of

https://github.com/nordlow/justd/blob/master/algorithm_ex.d#L148

in my C++ demanger module (not quite complete)

https://github.com/nordlow/justd/blob/master/mangling.d

This will make the bool conversion semantics of Optional![T|U] as
a return value in parsing/pattern-matching analogous with that of
string.


More information about the Digitalmars-d mailing list