Closed ianthehenry closed 1 year ago
I think the negative count thing is nice :+1:
I wonder if it might break some existing code though.
In many places in the std lib, -1 means the last member, so this is a very accurate addition. And there hardly can be code that only works with the old behavior.
In many places in the std lib, -1 means the last member
One that I made the connection for only recently is in the context of PEG specials. I had been puzzled for quite some time why -1
is used for what it is, but I think the above quote might apply (or is close in any case) :)
Not quite true: In the PEG module, -1
is not some special convention; it just follows from the meaning of the pattern: positive numbers mean "matches if there are this many characters (and advance)", whereas negative numbers mean "matches if there are not this many characters (and not advance)". So -1
will match if there is not at least 1 character available, which only is true for the end of the matched subject.
As a quick question re: this context. is my assumption that 0 means “always match” reasonable? I was playing around with ircv3 parsers and needed an “always match” and “never match” primitive for… reasons. I used 0 and “! 0”.
After thinking about it I opened a PR to just add true
and false
PEG semantics, since I think those are reasonable and are less error-prone in the end: https://github.com/janet-lang/janet/pull/1187
In the PEG module, -1 is not some special convention; it just follows from the meaning of the pattern: positive numbers mean "matches if there are this many characters (and advance)", whereas negative numbers mean "matches if there are not this many characters (and not advance)". So -1 will match if there is not at least 1 character available, which only is true for the end of the matched subject.
Ah, thanks for spelling it out like this. Much appreciated.
Though I guess:
"matches if there are not this many characters (and not advance)"
"this many" is a positive value (the absolute value of n).
This is a functional change, as previously a negative count would be treated the same as 0. But it seems unlikely to cause problems in practice.
This brings a satisfying symmetry to the quadrants of this "table:"
(first list)
(last list)
(drop 1 list)
(drop -1 list)
It might make sense to do the same thing for
take
, but becausetake
works with fibers, we can't support it completely.It might be preferable to have a separate
drop-last
function. The negative count thing seems nicer to me, but I don't know if there's precedent for it elsewhere in the standard library.