PDA

View Full Version : Adding a value to position in a list


dkennard
2007-06-28, 09:57 AM
Its been a long while since I programmed any Lisp, I've had a look through the forum but cant find a way to add to an element to a position in a list other then the start or end.

I have a list of 2d points:
((1.0 1.0) (2.0 2.0) (3.0 3.0) (4.0 4.0) (5.0 5.0))
and another 2d point:
(6.0 6.0)
I want to end up with the 2d point inserted into the list somewhere other then the first or last item eg:
((1.0 1.0) (2.0 2.0) (3.0 3.0) (6.0 6.0) (4.0 4.0) (5.0 5.0))

I'm guessing there is a simple way to do this but its got me stumped. Thanks for any advice you can give me.

kennet.sjoberg
2007-06-29, 12:24 AM
I have a list of 2d points:
(setq MyFirstList '((1.0 1.0) (2.0 2.0) (3.0 3.0) (4.0 4.0) (5.0 5.0)) )
and another 2d point:
(setq MyNextList '(6.0 6.0) )

I want to end up with the 2d point inserted into the list somewhere other then the first or last item eg:
((1.0 1.0) (2.0 2.0) (3.0 3.0) (6.0 6.0) (4.0 4.0) (5.0 5.0))

here is one way

(setq Index 0 )
(foreach Item_In MyFirstList
(setq Index (1+ Index ) )
(if (= Index 4 ) (setq MyResultList (append MyResultList (list MyNextList ))) ( ) )
(setq MyResultList (append MyResultList (list Item_In )))
)


: ) Happy Computing !

kennet

dkennard
2007-06-29, 04:26 AM
Ah - I get it now thanks Kennet.

CAB2k
2007-06-29, 03:03 PM
One more method:
;; by Reni U.
;;; Insert atom in list at pos n
(defun insert (lst x n)
(cond
((zerop n) (cons x lst))
(T (cons (car lst) (insert (cdr lst) x (1- n))))))