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

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

Re: Copying a string


From: tpeplt
Subject: Re: Copying a string
Date: Mon, 31 Jul 2023 14:23:29 -0400
User-agent: Gnus/5.13 (Gnus v5.13) Emacs/28.2 (gnu/linux)

uzibalqa <uzibalqa@proton.me> writes:

>
> I do not think it makes a difference, and that using (copy-sequence string)
> would be overkill. Right ? 
>
> (defun swap-chars (string p q)
>   "Swap characters at INDEX1 and INDEX2 in STRING."
>
>   (let* ( (char1 (elt string p))
>           (char2 (elt string q))
>           (mutant string))
>
>     (aset mutant p char2)
>     (aset mutant q char1)
>
>     mutant))

Let’s use Emacs and find out.

1. C-h f eq

> Return t if the two args are the same Lisp object.

2. C-h f equal

> Return t if two Lisp objects have similar structure and contents.
> They must have the same data type.
> Conses are compared by comparing the cars and the cdrs.
> Vectors and strings are compared element by element.

3. Next, comment out the two lines in ‘swap-chars’ that modify the local
variable ‘mutant’:

>     (aset mutant p char2)
>     (aset mutant q char1)

(setq my-str "abc")

(eq my-str (swap-chars my-str 0 2))
=> t

So, ‘my-str’ and the object returned by (swap-chars my-str 0 2) are the
same object.

4. Next, change ‘swap-chars’ to use ‘copy-sequence’, but with the ‘aset’
modifiers still commented out:

(defun swap-chars (string p q)
  "Swap characters at INDEX1 and INDEX2 in STRING."

  (let* ( (char1 (elt string p))
          (char2 (elt string q))
          (mutant (copy-sequence string)))

;;    (aset mutant p char2)
;;    (aset mutant q char1)

    mutant))

(eq my-str (swap-chars my-str 0 2))
=> nil

But the strings will have the same contents until the ‘aset’ modifiers
are restored to the procedure definition.

(equal my-str (swap-chars my-str 0 2))
=> t

Once the ‘aset’ modifiers are restored to the procedure, the definition
can be checked to confirm that it returns the expected value:

(equal "cba" (swap-chars my-str 0 2))
=> t

5. Help -> More Manuals -> Intro to Emacs Lisp

The Intro to Emacs Lisp provides examples with explanations that might
be of value to you.  Here are two sections that might be useful, but the
entire manual should be read to reach the point where it does not have
anything new to teach you, if you are going to be doing routine
programming in Emacs Lisp.

(info "(eintr) Lists diagrammed")
(info "(eintr) Counting function definitions")

--




reply via email to

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