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

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

RE: [External] : Re: List not getting filled up


From: Drew Adams
Subject: RE: [External] : Re: List not getting filled up
Date: Mon, 31 Jul 2023 00:50:41 +0000

> Each time you ‘push’ that string into your ‘result’ list, you are
> storing one more reference to the same string object. 
> 
> This explains why you get a list that looks like it contains 6
> identical strings — they are *the same* string.
> 
> Instead, you should be avoiding in-place string mutation and building
> new string instances as you go, perhaps by redefining ‘swap-chars’ to
> be non-destructive:
> 
>     (defun swap-chars (string p q)
>       "Swap chars in STRING at positions P and Q."
>       (cond
>        ((= p q) string)
>        ((> p q) (swap-chars string q p))
>        (t (concat
>            (substring string 0 p)
>            (substring string q (1+ q))
>            (substring string (1+ p) q)
>            (substring string p (1+ p))
>            (substring string (1+ q))))))
> 
> (This is likely not the fastest way to build a string with two
> characters swapped. Do not let that distract you from the goal. Your
> first goal is to get your program working correctly. When and if that
> happens, and when and if your working solution is deemed too slow,
> only then you start optimizing.)
> 
> (Adjusting the ‘permute’ function to non-destructive behavior of
> ‘swap-chars’ is left as an exercise. Hint 1: in your first
> ‘swap-chars’ call, you need to arrange for the return value to be
> passed to the recursive invocation of ‘permute’. Hint 2: your second
> ‘swap-chars’ call is only there to undo the modification made by the
> first call, so it could be avoided by introducing a local variable to
> hold the result of the modification.)

Another possibility is to go ahead and change
the string "destructively", over and over, but
create a new string from the result after each
modification, and add that new string to the
list.  You can do that with `copy-seq', `format',
or `concat'.

What's important to understand is what Yuri
explained, including the fact that how you get
get separate strings to add to the list is less
important than understanding that you need to
do that.  I'm only pointing out that you need
not forego the use of destructive modification
just because you need to end up with multiple,
separate strings.

reply via email to

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