Jump to content

Recommended Posts

Posted

Hello o/

I'm trying to adjust the second value in a list.
I'm not entirely sure about lists & the functions used to manipulate them, but this is what im trying (and failing):
 

(setq brgZ (list deg minu sec))
(setq (cadr brgZ) (+ (cadr brgZ) 1))

& i am getting the error:
error : invalid-identifier <(CADR BRGZ)> ; expected <SYMBOL> at [setq]

 

I've tried looking up how to modify the any value individually in a list, but am kind of struggling to find answers.

Explanations are super appreciated (I assume this is a really simple thing >_<)

Posted

(setq ..... _) wants a variable such as (setq brgZ ......)

In your example you are giving it a value rather than the variable

 

  • Like 1
Posted (edited)
On 7/13/2023 at 7:54 AM, Emmanuel Delay said:

Read this:
https://www.afralisp.net/autolisp/tutorials/list-manipulation.php

 

You want the subst function.

Syntax : (subst newitem olditem lst)

 

in your example

(setq brgZ
  (subst (+ 1 (cadr brgZ)) (cadr brgZ)  brgZ)
)

 

 

I wouldn't recommend using subst for this purpose, as subst will replace all occurrences within the list - consider the following example:

_$ (setq brgZ '(10 10 10))
(10 10 10)
_$ (subst (1+ (cadr brgZ)) (cadr brgZ) brgZ)
(11 11 11)

 

Instead, I would use simple list construction -

(setq brgZ (list (car brgZ) (1+ (cadr brgZ)) (caddr brgZ)))

 

Alternatively, you could use mapcar, but this somewhat obscures the intent:

(setq brgZ (mapcar '+ brgZ '(0 1 0)))

 

Edited by Lee Mac
  • Like 3
Posted

How about a general "replace nth element"

 

(defun c:test ( / ) 
	;; for example
	(setq deg 17)
	(setq minu 34)
	(setq sec 55)
	
	(setq brgZ (list deg minu sec))
	;; (setq (cadr brgZ) (+ (cadr brgZ) 1))
	(setq brgZ (replace_nth brgZ 1 (+ (cadr brgZ) 1) ))
	
)

;; replaces then nth item of a list
(defun replace_nth (lst n replaceBy / i res a)
	(setq res (list))
	(setq i 0)
	(foreach a lst
		(if (= i n)
			(setq res (append res (list replaceBy)))
			(setq res (append res (list a)))
		)
		(setq i (+ i 1))
	)
	res
)

 

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Unfortunately, your content contains terms that we do not allow. Please edit your content to remove the highlighted words below.
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...