change a number list item

change a number list item

GeryKnee
Advocate Advocate
224 Views
2 Replies
Message 1 of 3

change a number list item

GeryKnee
Advocate
Advocate

 

In the following

I want to change an item it's Itemaa 


(defun c:xx()
(setq NumList '(1 2 3 4 5))
;;Change e.g. third number from 3 to 10 ?
)

0 Likes
Accepted solutions (1)
225 Views
2 Replies
Replies (2)
Message 2 of 3

Kent1Cooper
Consultant
Consultant

Command: (setq test '(1 2 3 4 5))
(1 2 3 4 5)

 

To change the third item [whatever its value] to whatever you want:

 

Command: (subst 10 (nth 2 test) test)
(1 2 10 4 5)

 

But be aware that it will do it to all instances of the value in the target item if there are more than one, so if that's not wanted, write back:

 

Command: (subst 10 (nth 2 test) '(1 2 3 4 5 4 3 2 1))
(1 2 10 4 5 4 10 2 1)

Kent Cooper, AIA
0 Likes
Message 3 of 3

Sea-Haven
Mentor
Mentor
Accepted solution

This jumped out for me changes only 1 item.

 

 

;;---------------------=={ 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)))
        )
    )
)