August 19, 2024

P21 - Insert an element at a given position into a list

Example:* (insert-at 'alfa '(a b c d) 2)(A ALFA B C D)

lisp

;;; Function that receives an element, a list and a position ;;;
;;; and returns a new list that contains the element in the ;;;
;; desired. If the position requested is greater than the last of the ;;;
;;; list, insert at the end of the list.                       ;;

(defun insert-at (elem org-list pos)
    (if (or (eql pos 1) (eql org-list nil))
            (cons elem org-list)
            (cons (car org-list) (insert-at elem (cdr org-list) (- pos 1)))
Be first to comment
Leave a reply