On Wednesday, 10 October 2018 at 08:46:42 UTC, James Japherson wrote:
Would be nice to be able to pass $ as a function argument to be used in automatic path length traversing.

void foo(int loc)
{
   return bar[loc];
}

then foo($) would essentilly become

foo(&)

  becomes ==>

   return bar[$];


instead of having do to thinks like foo(bar.length).

The usefulness comes from the case when bar is local:

void foo(int loc)
{
   auto bar = double[RandomPInt+1];

   return bar[loc];
}


then foo($) always returns a value and the outside world does not need to know about foo. Since $ is a compile thing expression and not used anywhere else this can always be done(it is a symbolic substitution and has a direct translation in to standard D code except $ cannot be used as arguments like this the current D language grammar).

$ requires context (the array) for its value to be known - it's not a compile-time expression any more than rand() + currentWeather(getGpsCoordinates()) is. If $ were a valid identifier, you could do something like this:

struct Sentinel {}
Sentinel $;

void foo(T)(T loc) {
    auto bar = double[RandomPInt+1];
    static if (is(T == Sentinel)) {
        return bar[$];
    } else {
        return bar[loc];
    }
}

unittest {
    foo($);
}

Note that this would turn foo into a template, so that foo($) creates a separate function from foo(3).

Since $ isn't a valid identifier, this is currently impossible, but bachmeier's suggestion of foo!"$" works:

void foo(string s = "")(int loc = 0)
if (s == "" || s == "$") {
    auto bar = double[RandomPInt+1];
    static if (s == "$") {
        return bar[$];
    } else {
        return bar[loc];
    }
}

--
  Simen

Reply via email to