Hi,
as an improvement, would you be interested in making indices accept negative numbers, which apparently is something that other languages (e.g. python) offer?
Based on the existing code in cl-str I propose the semantics of the index to be defined as follows:
(defun index (string pos)
"Modular/saturating position in string.
Returns an index between 0 and (LENGTH STRING), inclusive.
If POS is NIL, the returned value is the length of STRING,
to be consistent with exclusive end indices.
Otherwise POS must be an integer.
If POS is positive, it is clamped to be at most the length
of the string.
If POS is negative and its magnitude is lower than the
length of string, the returned index is meant to represent
an offset from the end.
Otherwise, if POS is negative and its magnitude is greater
than the length, the returned index is 0.
EXAMPLES:
(flet ((is (pos res) (assert (= (index \"abcde\" pos) res))))
;; nil case
(is nil 5)
;; positive
(is 3 3)
(is 4 4)
(is 5 5)
(is 10 5)
;; negative
(is -1 4)
(is -2 3)
(is -3 2)
(is -4 1)
(is -5 0)
(is -10 0))
"
(check-type pos (or null integer))
(with-accessors ((length length)) string
(cond
((not pos) length)
((>= pos 0) (min pos length))
((< (abs pos) length) (+ length pos))
(t 0))))
If you are interested, I can add a patch that process indices in the existing functions through index to support negative indices, something that should be backward compatible AFAIK.
ok, this is not backward compatible considering substring clamps the index, so if some code relies on negative indices being clamped to zero, they'll have regressions.
Hi,
as an improvement, would you be interested in making indices accept negative numbers, which apparently is something that other languages (e.g. python) offer?
Based on the existing code in
cl-strI propose the semantics of the index to be defined as follows:If you are interested, I can add a patch that process indices in the existing functions through
indexto support negative indices, something that should be backward compatible AFAIK.ok, this is not backward compatible considering
substringclamps the index, so if some code relies on negative indices being clamped to zero, they'll have regressions.