[Top][All Lists]
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
Re: number-sequence
From: |
Kim F. Storm |
Subject: |
Re: number-sequence |
Date: |
20 Nov 2003 11:39:19 +0100 |
User-agent: |
Gnus/5.09 (Gnus v5.9.0) Emacs/21.3.50 |
Luc Teirlinck <address@hidden> writes:
> ===File ~/number-sequence.el================================
> (defun number-sequence (from &optional to inc)
> "Return a sequence of numbers from FROM to TO (both inclusive) as a list.
TO is only inclusive if there is an N for which TO = FROM + N * INC.
> INC is the increment used between numbers in the sequence.
> So, the Nth element of the list is (+ FROM (* N INC)) where N counts from
> zero.
> If INC is nil, it defaults to 1 (one).
> If TO is nil or numerically equal to FROM, return (FROM).
> If INC is positive and TO is less than FROM, or INC is negative
> and TO is larger than FROM, return nil.
> If INC is zero and TO is neither nil nor numerically equal to
> FROM, signal an error.
> Note that FROM, TO and INC can be integer or float."
> (if (or (not to) (= from to))
> (list from)
> (or inc (setq inc 1))
> (when (zerop inc) (error "The increment can not be zero"))
> (let (seq)
> (if (> inc 0)
> (while (<= from to)
> (setq seq (cons from seq)
> from (+ from inc)))
> (while (>= from to)
> (setq seq (cons from seq)
> from (+ from inc))))
When we are using floats here, there is a risk of accumulating errors,
and thus not getting the exact TO value into the list.
This could be better (but marginally slower):
(let (seq (n 0) (next from))
(if (> inc 0)
(while (<= next to)
(setq seq (cons next seq)
n (1+ n)
next (+ from (* inc n))))
(while (>= next to)
(setq seq (cons next seq)
n (1+ n)
next (+ from (* inc n))))
--
Kim F. Storm <address@hidden> http://www.cua.dk