between and among: worth Phobosization? (reprise)

Jesse Phillips via Digitalmars-d digitalmars-d at puremagic.com
Thu Mar 26 08:38:57 PDT 2015


On Sunday, 15 March 2015 at 01:48:53 UTC, Andrei Alexandrescu 
wrote:
> On 12/16/13 12:38 PM, Andrei Alexandrescu wrote:
>> bool between(T, U1, U2)(T v, U1 lo, U2 hi)
>> {
>>     return v >= lo && v <= hi;
>> }
>>
>> uint among(T, Us...)(T v, Us vals)
>> {
>>     foreach (i, U; Us)
>>     {
>>         if (v == vals[i]) return i + 1;
>>     }
>>     return 0;
>> }
>>
>> Add?
>
> Looks like among() has proven its worth since we introduced it. 
> Now I somehow forgot between() didn't make it, and reviewed 
> some code at work assuming it exists! Here's the original and 
> proposed in a couple of snippets:
>
> return (path.asPath.logicalLength() <= asPathLengths_[1] &&
>             path.asPath.logicalLength() >= asPathLengths_[0]);
>
> =>
>
> return path.asPath.logicalLength.between(asPathLengths_[0], 
> asPathLengths_[1]);
>
> ====
>
> if (prefix.prefixLen > prefixLenRange_[1] ||
>         prefix.prefixLen < prefixLenRange_[0]) {
>
> =>
>
> if (!prefix.prefixLen.between(prefixLenRange_[0], 
> prefixLenRange_[1])) {
>
> ====
>
> Well?
>
>
> Andrei

I think it would be a good addition. Would we want to allow 
specifying the inclusion like below:

     auto between(string inclusion = "[]")(int v, int a, int b) {
         static if(inclusion == "(]")
             return (v <= b && v > a);
         else static if(inclusion == "[)")
             return (v < b && v >= a);
         else static if(inclusion == "()")
             return (v < b && v > a);
         else static if(inclusion == "[]")
             return (v <= b && v >= a);
         else
             static assert(false, "unknown inclusion parameter");
     } unittest {
         static assert(4.between(3,5));
         static assert(4.between(4,5));
         static assert(4.between(3,4));

         static assert(!4.between!"(]"(4,5));
         static assert(!4.between!"[)"(3,4));
     }


More information about the Digitalmars-d mailing list