On Friday, 29 December 2017 at 20:33:22 UTC, Jonathan M Davis
wrote:
Well, I don't know what you're really doing in code here, but
in general, you'd write your code in a way that it checks empty
and simply doesn't try to do anything with front if the range
is empty.
Yes, ideally, if programmers were perfect, this would work. The
same applies to always checking null before dereferencing a
pointer. You can of course try and make sure you always do check
first. Or you can provide a safe way to do it in cases where you
only want to dereference a pointer if the pointer is not null.
Granted in some situations you want to crash as well because it
would indeed be a bug if a pointer was null (or a range was
empty).
Btw, it seems that phobos, or at lest some of it, has an
assert(!empty, "Attempting to fetch the front of an empty
filter."). I guess probably it's not everywhere so hence the
weird behavior you say happens sometimes :( ... ah well.
You could wrap the range in a range that specifically returns
some default element when the wrapped range is empty, meaning
that the range would then be infinite.
You could just use a wrapper function to call front and have it
return a Nullable or a default value if the range is empty, but
that wouldn't work when passing the range to other functions.
You could also do something like an infinite range that simply
returns the same value forever no matter how often front gets
popped, and then you could use chain to combine your range and
that range into a single range that would iterate through your
range and then give the same element forever.
Regardless, you'll have to be careful of any solution that
involves creating an infinite range, since while some
algorithms will be fine with it, others will either not compile
or result in an infinite loop (e.g. don't use foreach on it).
True, having to deal with infinite ranges will add to number of
cases I'd have to worry about. Would prefer not to of course.
I'm going to explore the Nullable approach you mentioned a bit me
thinks !
Also, I found this now:
https://forum.dlang.org/post/[email protected]
. Seems to be what I'm looking for!
Regardless, if you want to return an element when there isn't
one, you're going to have to come up with a value for that.
It's not something that's really going to work well generically.
The generic constructs would occur ideally before accessing
front. If not then yes, you're correct. Passing a "safeFront", or
any other non-range value further down the pipeline would need a
an undo function the other end of the pipeline.
- Re: How do you safely deal with r... aliak via Digitalmars-d-learn
-