2

I'm trying to define a value type which either holds a size_t or a null (which is what I mean by a 'maybe type'). What I want to be able to do is something like this (where the relevant type is Maybe!size_t:

 Maybe!size_t something_which_could_fail (int foo) {
      if (foo < 0) { return null;}
      else { return foo;}
 }

How would I implement such a thing? Ideally, I would like to be able to make it a template (so I could have other Maybe types as well), and have conversions from maybe to non-maybe types be possible as above (although I don't mind typecasting if this is not possible). It would also be nice if I could do something like this:

Maybe!size_t a = 50;
Maybe!size_t b = null;
Koz Ross
  • 3,040
  • 2
  • 24
  • 44

2 Answers2

11

What about Nullable type in phobos library? http://dlang.org/phobos/std_typecons.html#.Nullable

And some other info in D forum: D forum thread about Option(Maybe) type

Kozzi11
  • 2,413
  • 12
  • 17
4

Another option is to use std.variant.Algebraic. This is similar to the algebraic data types found in many functional languages, but implemented in the library. I'm not sure how much I would recommend this option, as it's a bit obtuse at times to work with. However, you can do it.

import std.variant;
import std.stdio;

//For convenience as typeof(null) has no name
alias Null = typeof(null);

alias Maybe(T) = Algebraic!(T, Null);

void main()
{
    Maybe!int n = 0;
    writeln(n); //Prints "0"

    n = null;
    writeln(n); //Prints "null"

    //Prints "I'm Null!"
    n.visit!(
        (int  i) => writeln("I'm an int!"),
        (Null n) => writeln("I'm Null!"),
    );

    auto m = n.visit!(
        (int  i) =>  i,
        (Null n) => -1,
    );
    writeln(m); //Prints "-1"
}
Meta
  • 1,091
  • 6
  • 14