Insert Nth

Function Syntax (LM:InsertNth <x> <n> <l>)
Current Version 1.0
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

Program Description

This function will insert an item at the nth position in a list.

Recursive Version

Select all
;;----------------------=={ Insert Nth }==--------------------;;
;;                                                            ;;
;;  Inserts an item at the nth position in a list.            ;;
;;------------------------------------------------------------;;
;;  Author: Lee Mac, Copyright © 2011 - www.lee-mac.com       ;;
;;------------------------------------------------------------;;
;;  Arguments:                                                ;;
;;  x - item to be inserted                                   ;;
;;  n - zero-based index at which to insert item              ;;
;;  l - list in which item is to be inserted                  ;;
;;------------------------------------------------------------;;
;;  Returns:  List with item inserted at nth position         ;;
;;------------------------------------------------------------;;

(defun LM:InsertNth ( x n l )
  (if (and l (< 0 n))
    (cons (car l) (LM:InsertNth x (1- n) (cdr l)))
    (cons x l)
  )
)

Iterative Version

Select all
;;----------------------=={ Insert Nth }==--------------------;;
;;                                                            ;;
;;  Inserts an item at the nth position in a list.            ;;
;;------------------------------------------------------------;;
;;  Author: Lee Mac, Copyright © 2011 - www.lee-mac.com       ;;
;;------------------------------------------------------------;;
;;  Arguments:                                                ;;
;;  x - item to be inserted                                   ;;
;;  n - zero-based index at which to insert item              ;;
;;  l - list in which item is to be inserted                  ;;
;;------------------------------------------------------------;;
;;  Returns:  List with item inserted at nth position         ;;
;;------------------------------------------------------------;;

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

Example Function Call

_$ (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