How do you safely deal with range.front?
aliak
something at something.com
Sat Dec 30 19:00:07 UTC 2017
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.
More information about the Digitalmars-d-learn
mailing list