diff options
author | Kaz Kylheku <kaz@kylheku.com> | 2022-04-14 21:29:25 -0700 |
---|---|---|
committer | Kaz Kylheku <kaz@kylheku.com> | 2022-04-14 21:29:25 -0700 |
commit | aeca5d81592de6bdbf485505fa867e36301d726a (patch) | |
tree | 82007d53f603cc6dded9f5949178da735ee31133 | |
parent | e33a5c88d867eb8b7e518d9ca113757d8c5f650e (diff) | |
download | cppawk-aeca5d81592de6bdbf485505fa867e36301d726a.tar.gz cppawk-aeca5d81592de6bdbf485505fa867e36301d726a.tar.bz2 cppawk-aeca5d81592de6bdbf485505fa867e36301d726a.zip |
cons: document nth and nthcdr; add tests
Fixing semantics of nth for negative values.
-rw-r--r-- | cppawk-cons.1 | 70 | ||||
-rw-r--r-- | cppawk-include/cons-priv.h | 2 | ||||
-rw-r--r-- | testcases-cons | 20 |
3 files changed, 91 insertions, 1 deletions
diff --git a/cppawk-cons.1 b/cppawk-cons.1 index 563f449..c1cb640 100644 --- a/cppawk-cons.1 +++ b/cppawk-cons.1 @@ -1367,6 +1367,76 @@ returns position(4, list(1, 2, 3)) -> nil .ft R +.SS Functions \fInth\fP and \fInthcdr\fP +.bk +Syntax: + +.ft B + nth(\fIi\fP, \fIx\fP) + nthcdr(\fIi\fP, \fIx\fP) +.ft R + +The +.B nth +and +.B nthcdr +functions perform zero-based indexing on lists. + +.B nth +retrieves the +.IR i -th +item of the list +.IR x . +If +.I i +is zero, it finds the first item; if +.I i +is one, the second item and so forth. +If there is no such item, +.B nth +returns +.BR nil . + +.B nthcdr +produces the suffix of the list +.I x +starting at the +.IR i -th +item, using the same numbering. + +Thus, there is a relationship between the two functions: + +.ft B + nth(\fIi\fP, \fIx\fP) <--> car(nthcdr(\fIi\fP, \fIx\fP)) +.ft R + +.B Examples: + +.ft B + nth(1, list(1, 2, 3)) -> 2 + nth(15, list(1, 2, 3)) -> nil + nthcdr(0, list(1, 2, 3)) -> (1 2 3) + nthcdr(2, list(1, 2, 3)) -> (3) +.ft R + +.B cons +cell of the list. The +.B nth +function finds the +.B car +of that +.B cons +cell. + +If +.I i +is a negative integer, then +.B nth +returns nil and +.B nthcdr +returns +.BR x . + .SH "SEE ALSO" cppawk(1) diff --git a/cppawk-include/cons-priv.h b/cppawk-include/cons-priv.h index 4c0a767..2f5bdce 100644 --- a/cppawk-include/cons-priv.h +++ b/cppawk-include/cons-priv.h @@ -693,7 +693,7 @@ function __nth(__pos, __lst) { for (; __pos > 0 && !__endp(__lst); __pos--) __lst = __cdr(__lst) - return __car(__lst) + return __pos == 0 ? __car(__lst) : __nil } function __nthcdr(__pos, __lst) diff --git a/testcases-cons b/testcases-cons index 6d14401..6211be6 100644 --- a/testcases-cons +++ b/testcases-cons @@ -599,3 +599,23 @@ BEGIN { nil nil nil +-- +33: +$cppawk ' +#include <cons.h> + +BEGIN { + print sexp(nth(-1, list(1, 2, 3))) + print sexp(nth(1, list(1, 2, 3))) + print sexp(nth(15, list(1, 2, 3))) + print sexp(nthcdr(0, list(1, 2, 3))) + print sexp(nthcdr(2, list(1, 2, 3))) + print sexp(nthcdr(-1, list(1, 2, 3))) +}' +: +nil +2 +nil +(1 2 3) +(3) +(1 2 3) |