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

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

Re: Understanding the "let" construct and the setting of variables


From: tomas
Subject: Re: Understanding the "let" construct and the setting of variables
Date: Fri, 18 Dec 2020 18:48:28 +0100
User-agent: Mutt/1.5.21 (2010-09-15)

On Fri, Dec 18, 2020 at 06:14:04PM +0100, Emanuel Berg via Users list for the 
GNU Emacs text editor wrote:
> steve-humphreys wrote:
> 
> > Let's introspect two questions.
> >
> > 1. In what simple circumstances would one use a "setq" in
> >    the body of a let?
> 
> When one wants to change a global variable that already exists
> outside of the function.

Or a local, if that has been locally bound, e.g. by a let or
a function param:

(defun collatz-sequence (n) ; [1]
  (while (> n 1)
    (insert (format "%5d\n" n))
    (setq n (if (= (mod n 2) 0) (/ n 2) (+ (* n 3) 1)))))

(collatz-sequence 11)
=>
   11
   34
   17
   52
   26
   13
   40
   20
   10
    5
   16
    8
    4
    2

Yeah, the 1 at the end is missing. Left as an exercise for
the reader :)

The setq in the function's last line modifies the n which
is local to the function, because it's in the parameter
list (which is roughly equivalent to a let list).

Cheers

[1] https://en.wikipedia.org/wiki/Collatz_conjecture

 - t

Attachment: signature.asc
Description: Digital signature


reply via email to

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