janet-lang / janet

A dynamic language and bytecode vm
https://janet-lang.org
MIT License
3.52k stars 227 forks source link

drop with a negative count now drops from the end #1114

Closed ianthehenry closed 1 year ago

ianthehenry commented 1 year ago

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:"

It might make sense to do the same thing for take, but because take 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.

sogaiu commented 1 year ago

I think the negative count thing is nice :+1:

I wonder if it might break some existing code though.

pepe commented 1 year ago

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.

sogaiu commented 1 year ago

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) :)

zevv commented 1 year ago

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.

CosmicToast commented 1 year ago

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”.

CosmicToast commented 1 year ago

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

sogaiu commented 1 year ago

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).