Sublist
Function Syntax | (LM:sublst <lst> <idx> <len>) |
Current Version | 1.0 |
Donate |
Arguments | ||
---|---|---|
Symbol | Type | Description |
lst | List | List from which sublist is to be returned |
idx | Integer | Zero-based index at which to start the sublist |
len | Integer | The length of the sublist or nil to return all items above the starting index |
Returns | ||
Type | Description | |
List | A sublist of the supplied list |
Function Description
This function is the list equivalent of the AutoLISP substr function, and will return the sublist of a supplied list from a specified starting index and with a specified length.
Similar to the substr function, the length argument is optional and, if nil, this function will return all items above the specified starting index. However, unlike the substr function, the starting index for this function is zero-based (i.e. the first item in the list has index 0) to match the standard behaviour of other AutoLISP list functions.
Recursive Version
;; Sublst - Lee Mac ;; The list analog of the substr function ;; lst - [lst] List from which sublist is to be returned ;; idx - [int] Zero-based index at which to start the sublist ;; len - [int] Length of the sublist or nil to return all items following idx (defun LM:sublst ( lst idx len ) (cond ( (null lst) nil) ( (< 0 idx) (LM:sublst (cdr lst) (1- idx) len)) ( (null len) lst) ( (< 0 len) (cons (car lst) (LM:sublst (cdr lst) idx (1- len)))) ) )
Iterative Version
;; Sublst - Lee Mac ;; The list analog of the substr function ;; lst - [lst] List from which sublist is to be returned ;; idx - [int] Zero-based index at which to start the sublist ;; len - [int] Length of the sublist or nil to return all items following idx (defun LM:sublst ( lst idx len / rtn ) (setq len (if len (min len (- (length lst) idx)) (- (length lst) idx)) idx (+ idx len) ) (repeat len (setq rtn (cons (nth (setq idx (1- idx)) lst) rtn))) )
Example Function Calls
_$ (LM:sublst '(1 2 3 4 5 6 7 8) 2 4) (3 4 5 6) _$ (LM:sublst '(1 2 3 4 5 6 7 8) 2 nil) (3 4 5 6 7 8)