between and among: worth Phobosization?

Chris Cain clcain at uncg.edu
Mon Dec 16 17:02:26 PST 2013


On Monday, 16 December 2013 at 20:38:52 UTC, Andrei Alexandrescu 
wrote:
> bool between(T, U1, U2)(T v, U1 lo, U2 hi)
> {
>     return v >= lo && v <= hi;
> }

I realize this is, at this point, being retracted. But it would 
open up some interesting ideas. It seems a lot like iota, but it 
could look pretty cool for some purposes. Consider an alternative 
API where you could do things like this:

---
if(x in between(2, 7)) {
    //...
}
---

and

---
// for random number generation...
auto a = uniform(between(30, 100));
---

A slight bit more verbose but more readable, maybe. It also 
shifts the code that checks that it's a valid range (not in the D 
InputRange sense) to between instead.

So code like
https://github.com/D-Programming-Language/phobos/blob/master/std/random.d#L1318
could be taken out and isolated in the "between" code. This could 
have some slight positive performance implications for cases 
where you generate a lot of random numbers in the same range, but 
its main value would probably come improved readability and 
reduced code duplication (but, admittedly, I've not looked around 
enough to know if there are more opportunities to use such a 
between object in phobos...).

Also, kinda going along with what bearophile said, something like 
this might be possible to add to iota. But I'd like to see a 
different name for it since `uniform(iota(30,100))` isn't exactly 
as nice to read.

And I think a default for the range of numbers between represents 
probably should be "[)" but obviously being customizable is 
important too.


More information about the Digitalmars-d mailing list