Insert Nth

Function Syntax (LM:insertnth <x> <n> <l>)
Current Version 1.0
Donate
Arguments
Symbol Type Description
x List or Atom Item to be inserted
n Integer Zero-based index at which to insert item
l List List in which item is to be inserted
Returns
Type Description
List List with item inserted at nth position

Function Description

This function will insert an item ('x') at the nth position in a list ('l').

The index n is zero-based (that is, the first position in the list has index 0) in line with standard AutoLISP functions and most other programming conventions. If the supplied index is less than zero or greater than or equal to the number of items in the list, the supplied list will be returned without modification.

Recursive Version

Select all
;; Insert Nth  -  Lee Mac
;; Inserts an item at the nth position in a list.
;; x - [any] Item to be inserted
;; n - [int] Zero-based index at which to insert item
;; l - [lst] List in which item is to be inserted

(defun LM:insertnth ( x n l )
    (cond
        (   (null l) nil)
        (   (< 0  n) (cons (car l) (LM:insertnth x (1- n) (cdr l))))
        (   (cons x l))
    )
)

Iterative Version

Select all
;; Insert Nth  -  Lee Mac
;; Inserts an item at the nth position in a list.
;; x - [any] Item to be inserted
;; n - [int] Zero-based index at which to insert item
;; l - [lst] List in which item is to be inserted

(defun LM:insertnth ( x n l / i )
    (setq i -1)
    (apply 'append (mapcar '(lambda ( a ) (if (= n (setq i (1+ i))) (list x a) (list a))) l))
)

Example Function Calls

_$ (LM:insertnth "A" 3 '(0 1 2 3 4 5))
(0 1 2 "A" 3 4 5)
_$ (LM:insertnth 1 4 '("A" "B" "C" "D" "E"))
("A" "B" "C" "D" 1 "E")

textsize

increase · reset · decrease

Designed & Created by Lee Mac © 2010