Subst Nth

Function Syntax (LM:SubstNth <a> <n> <l>)
Current Version 1.0
Arguments
Symbol Type Description
a List or Atom Item to substitute
n Integer Position in List to substitute the Item
l List List in which to make the substitution
Returns
Type Description
List Resultant list following the substitution

Program Description

This subfunction will substitute a supplied item for the item found the nth position in a supplied list.

Recursive Version

Select all
;;---------------------=={ Subst Nth }==----------------------;;
;;                                                            ;;
;;  Substitutes an item at the nth position in a list.        ;;
;;------------------------------------------------------------;;
;;  Author: Lee Mac, Copyright  2011 - www.lee-mac.com       ;;
;;------------------------------------------------------------;;
;;  Arguments:                                                ;;
;;  a - item to substitute                                    ;;
;;  n - position in list to make the substitution             ;;
;;  l - list in which to make the substitution                ;;
;;------------------------------------------------------------;;
;;  Returns:  Resultant list following the substitution       ;;
;;------------------------------------------------------------;;

(defun LM:SubstNth ( a n l )
    (if l
        (if (zerop n)
            (cons a (cdr l))
            (cons (car l) (LM:SubstNth a (1- n) (cdr l)))
        )
    )
)

Iterative Version

Select all
;;---------------------=={ Subst Nth }==----------------------;;
;;                                                            ;;
;;  Substitutes an item at the nth position in a list.        ;;
;;------------------------------------------------------------;;
;;  Author: Lee Mac, Copyright  2011 - www.lee-mac.com       ;;
;;------------------------------------------------------------;;
;;  Arguments:                                                ;;
;;  a - item to substitute                                    ;;
;;  n - position in list to make the substitution             ;;
;;  l - list in which to make the substitution                ;;
;;------------------------------------------------------------;;
;;  Returns:  Resultant list following the substitution       ;;
;;------------------------------------------------------------;;

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

Example Function Call

_$ (LM:SubstNth 10 3 '(0 1 2 3 4 5))
(0 1 2 10 4 5)

textsize

increase · reset · decrease

Designed & Created by Lee Mac © 2010