help-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: [Elisp][Question] How to modify a list by index while preserving val


From: Rodrigo Morales
Subject: Re: [Elisp][Question] How to modify a list by index while preserving value outside of scope?
Date: Sun, 20 Aug 2023 04:08:29 +0000

Here's a simpler example.

---
(defun my/f2 (foo)
  (setf (nth 0 foo) 12))

(defun my/f1 (foo)
  (princ (format "%s\n" foo))
  (my/f2 foo)
  (princ (format "%s\n" foo)))

(let ((items (list 1 2 3)))
  (my/f1 items))
---

---
(1 2 3)
(12 2 3)
---

Today I learned that `setf' can be used inside functions to change the
value of lists and see those changes outside of the function. I
wrongly believed that whenever function parameters were passed by copy
and there was no way to see the changes reflected outside of the
function (i.e. the only way would be to return a value).

Relevant information on this topic is appreciated.

On Sun, 20 Aug 2023 at 03:46, Rodrigo Morales
<moralesrodrigo1100@gmail.com> wrote:
>
> ----
> (defun my/f (foo bar)
>   (princ (format "(foo: %s) (bar: %s)\n" foo bar))
>   (cond
>    (foo (setf (nth 0 bar) "100"))
>    (t (my/f "apples" bar)
>       (my/f "bananas" bar))))
>
> (my/f nil (list 123))
> ----
>
> ---
> (foo: nil) (bar: (123))
> (foo: apples) (bar: (123))
> (foo: bananas) (bar: (100))
> ---
>
> I have some questions:
>
> + The second time my/f function is called (i.e. when "apples" is
>   passed), `bar' equals `123'. The third time `my/f' is called
>   (i.e. when "bananas" is passed), `bar' has a different value. We can
>   conclude that the modification to `bar' in the second call affected
>   the third call. How is this possible? `bar' is an argument of `my/f',
>   as far as I'm concerned, any modification to a variable that is a
>   function parameter only affects the scope of the function.
> + This is a minimal working example, in reality, the code I'm writing is
>   more complex. In the code that I'm writing, `bar' is a list and I want
>   to modify some of their elements by index. The only way I know is by
>   using `(setf (nth index my-list) new-value)'. However, using this
>   method seems to changes the value of the variable outside of the
>   function call. Are there any other ways to modify a list by index
>   without affecting its value outside of the function call?



reply via email to

[Prev in Thread] Current Thread [Next in Thread]