On 6/10/22 10:22, Antonio wrote:
> Is there any alternative to ***range front*** that returns a Nullable
> (i.e. **frontAsMonad** or **frontAsNullable**)?

import std;

// Spelling? :)
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 range algorithms like save(), etc. here
  }

  return Nullablelize();
}

void main() {
  // Wow! We can take 10 elements without error. :)
  writeln(iota(5)
          .filter!(i => i % 2)
          .nullablelize
          .take(10));
}

Ali

Reply via email to