Passing $ as a function argument

Simen Kjærås simen.kjaras at gmail.com
Thu Oct 11 06:58:08 UTC 2018


On Wednesday, 10 October 2018 at 23:04:46 UTC, James Japherson 
wrote:
> The whole point is not to use $ as an identifier but to specify 
> to the compiler of that it can rewrite it.

I know. I'm pointing out that as syntactic sugar, it can't be 
passed as an int.


> You seem to think that what the compiler does is absolute 
> authority. This is why I said "It would be nice".... meaning 
> that if we had some a feature(which is entirely doable, not 
> some mathematical impossibility), it would allow one to express 
> the limit of an index in a concise way. Your templated version 
> is not concise. All you really proved is that the compiler can 
> be given a rewrite rule and handle this nicely.
>
> $ is not an used for identifiers, it is used to specify that 
> the maximum length of the array it is used in is to be used. It 
> is short hand for doing hacks such as specifying -1 for maximum 
> length, etc.
>
> You seem to to have not understood the problem.
>
> I mean, don't you understand that the entire point of $ in the 
> first place is just syntactic sugar?

I do. Do you understand what syntactic sugar even is? Do you 
understand what an int is? Do you understand what a compiler is 
and does? Do you have any idea what separate compilation is?

Now, to spell it out: $ is syntactic sugar that is replaced with 
the .length or .opDollar property of the array/range used in the 
surrounding expression. It is valid in arr[$-1] exactly because 
arr is an array that provides the necessary context. The result 
of an expression using $ is generally a size_t, but can be any 
type when the range overloads opDollar. The behavior of $ as 
something you can pass around in other contexts is not easy to 
pin down.

Consider:

struct MyRange {
     string opDollar() { return "foo!"; }
     bool opIndex(size_t idx) { return false; }
     bool opIndex(string idx) { return true; }
}

bool fun(size_t idx) {
     MyRange mr;
     return mr[idx];
}

unittest {
     auto x = fun($); // What does it even mean?
}


> It also has no context in and of itself. The compiler knows 
> what to do with it... The same can be done with function 
> arguments. You just haven't thought about the problem enough.

Then please, show me how it works in my and others' examples.

The compiler only know what we tell it. Your description of this 
feature is woefully inadequate at providing the information 
necessary to tell the compiler how to do this.

Now, I and others may have come off as slightly... dismissive. 
It's not that we don't like your idea, we just see a lot of 
problems with it. There may be solutions to these, and if you 
have said solutions, we'd love to see them. You'll need to give a 
more technical description than you have thus far, though.

--
   Simen


More information about the Digitalmars-d mailing list