On Friday, 29 December 2017 at 20:47:44 UTC, Dukc wrote:
On Friday, 29 December 2017 at 19:38:44 UTC, aliak wrote:
So when I'm dealing with ranges, there're a number of times where I get the front of the returned result of a set of operations, but of course there is no front so you get an runtime access error.

This could be what you want:

auto makeInfinite(Range)(Range ofThis)
{   import std.range;
    return ofThis.chain(typeof(ofThis.front).init.repeat);
}

void main()
{   import std.stdio, std.range;
    auto testArray = [2, 3, 4].makeInfinite;
    foreach(e; testArray.take(5)) e.writeln;
    readln(); //stops the console from closing immediately;
}

/+
2
3
4
0
0
+/

Hmm, interesting. Not sure that's what I'm looking for but I like it anyway :)

I'm more looking to deal with situations like this:

Instead of this:
  auto result = range.op!f;
  if (!result.empty) {
    result.front.method();
  }

This:
  range.op!f.ifFront.method();


In the above scenario I only want method to be called if the pipeline resulted in any element left in the range.

On the other hand, I really do not recommend using ranges that way as a default. Most often you do not want to call front() or popFront() of an empty range in the first place. So if you end up doing so accidently, you want to know it. If it just returned some default value chances would be you never notice you have a bug. That's why front() in debug mode is usually programmed to termitate the program when it's called incorrectly.

True you don't want to call front on empty, but sometimes I only care to call a method on front if it's there. Where the situation necessitates the existence of front, and not having a front is indeed a bug, then you want the program to terminate, yes. But not otherwise.


Reply via email to