1

Early beginner here. I'm looking for a function that takes a list and changes only its first element, using some function or other. I realize setcar sort of does that, but it also changes the initial list. Thus if I have

(setq mylist '("Red" "Green" "Blue"))

and then run

(setcar mylist (downcase (car mylist))

the value of mylist will change to ("red" "Green" "Blue").

What I'm looking for, though, is a function that only outputs the value that setcar will set mylist to but does not change the value of mylist.

I realize I could do, e.g.

(setq mynewlist mylist)
(setcar mynewlist (downcase (car mynewlist))

and get essentially the same result. But I wanted to know if this is the best way to do it.

  • Ask your question about a variable as a separate question, please. One question per question. – Drew Sep 17 at 17:45
2

I think you're asking for a function that returns a new list whose car is a value you provide and whose cdr is a copy of the cdr of the original list. That way, there is no modification of the original list, and the resulting list shares no structure with the original.

(defun foo (new-car-val xs)
  "..."
  (cons new-car-val (copy-sequence (cdr xs))))

(foo (downcase (car mylist)) mylist)

By the way, this is not what you want:

(setq mylist '("Red" "Green" "Blue"))

(setq mynewlist mylist)
(setcar mynewlist (downcase (car mynewlist)))

That modifies the original list, mylist, and mynewlist. They are the same list.

If you don't want to share list structure, use copy-sequence.

See nodes car, cdr, cons and List Implementation of manual Intro to Emacs Lisp Programming.


Update, from the comments:

Q: So am I right in thinking that (setq var1 var2) doesn't 'store' the current value of var2 but rather 'tells' var1 to always point to whatever var2 is pointing to? Maybe I'm mixing too many metaphors here.

A: Yes, depending on what you mean. It sets the value of var1 to whatever the value of var2 is - the actual thing, not a copy. If the value of var2 is a list, then the value of var1 is set to that same list, not a copy.

| improve this answer | |
  • So much to learn! Your answer just made me realize there are very many things about lists I do not understand. I need to do my homework better. – apc Sep 17 at 17:57
  • So am I right in thinking that (setq var1 var2) doesn't 'store' the current value of var2 but rather 'tells' var1 to always point to whatever var2 is pointing to? Maybe I'm mixing too many metaphors here... – apc Sep 17 at 18:02
  • 1
    Yes, depending on what you mean. It sets the value of var1 to whatever the value of var2 is - the actual thing, not a copy. If the value of var2 is a list, then the value of var1 is set to that same list, not a copy. – Drew Sep 17 at 18:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.