当前位置:网站首页>D interval to nullable conversion

D interval to nullable conversion

2022-06-11 13:32:00 fqbqrr

original text
Convert to nullable :

@safe Nullable!Item getItem(int _id)
  {
    
    import std.algorithm : filter;

    with (items.filter!(item => item.id == _id))
    {
    
      if (empty)
        return Nullable!Item.init;
      else
        return front.nullable;
    }
  }

such :

import std;

//  spell ?
auto nullablelize(R)(R range) {
    
  alias E = Nullable!(ElementType!R);

  struct Nullablelize {
    
    enum empty = false;

    auto front() {
    
      if (range.empty) {
    
        return E();

      } else {
    
        return E(range.front);
      }
    }

    void popFront() {
    
      if (!range.empty) {
    
        range.popFront();
      }
    }

    //  Other interval algorithms , Such as save(), wait 
  }

  return Nullablelize();
}

void main() {
    
  //  Take 10 That's right .
  writeln(iota(5)
          .filter!(i => i % 2)
          .nullablelize
          .take(10));
}

It was used Auxiliary method + structure , Or so :

import std.range, std.typecons;

Nullable!(ElementType!R) maybeFront(R)(auto ref R r)if (isInputRange!R)
{
    // Take the element type .
    if (r.empty)
        return typeof(return)();// Return type .
    else
        return nullable(r.front);// Can be empty .
}

unittest
{
    
    int[] a = [1, 2, 3];
    int[] b;

    assert(a.maybeFront == nullable(1));
    assert(b.maybeFront.isNull);
}
原网站

版权声明
本文为[fqbqrr]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206111323428444.html