Advertisement
Guest User

option.d

a guest
Sep 8th, 2013
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
D 1.66 KB | None | 0 0
  1. template isNullableType(T) {
  2.     enum isNullableType = __traits(compiles, T.init is null);
  3. }
  4.  
  5. struct Option(T) {
  6. private:
  7.     static if (isNullableType!T) {
  8.         T _value;
  9.  
  10.         pure @safe nothrow
  11.         this(T value) {
  12.             _value = value;
  13.         }
  14.     } else {
  15.         T _value;
  16.         bool _isSome;
  17.  
  18.         pure @safe nothrow
  19.         this(T value) {
  20.             _value = value;
  21.             _isSome = true;
  22.         }
  23.     }
  24. public:
  25.     pure @safe nothrow
  26.     bool isNone() const {
  27.         static if (isNullableType!T) {
  28.             return _value is null;
  29.         } else {
  30.             return !_isSome;
  31.         }
  32.     }
  33.  
  34.     pure @safe
  35.     inout(T) get() inout {
  36.         if (isNone) {
  37.             throw new Exception("get called on an empty Option type!");
  38.         }
  39.  
  40.         return _value;
  41.     }
  42.  
  43.     @trusted
  44.     string toString() const {
  45.         import std.conv;
  46.  
  47.         if (isNone) {
  48.             return "None";
  49.         } else {
  50.             return "Some(" ~ to!string(_value) ~ ")";
  51.         }
  52.     }
  53. }
  54.  
  55. pure @safe nothrow
  56. Option!T none(T)()
  57. out(val) {
  58.     assert(val.isNone);
  59. } body {
  60.     return Option!T.init;
  61. }
  62.  
  63. pure @safe nothrow
  64. inout(Option!T) some(T)(inout(T) value)
  65. out(val) {
  66.     assert(!val.isNone);
  67. } body {
  68.     return Option!T(value);
  69. }
  70.  
  71. auto map(alias fun, T)(Option!T option) {
  72.     alias typeof(fun(option._value)) R;
  73.  
  74.     if (!option.isNone) {
  75.         return some(fun(option._value));
  76.     }
  77.  
  78.     return none!R();
  79. }
  80.  
  81. auto otherwise(T, TC)(Option!T option, lazy TC alternative)
  82. if(is(TC : T)) {
  83.     if (!option.isNone) {
  84.         return option._value;
  85.     }
  86.  
  87.     return alternative();
  88. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement