# IntList

Starting with emacs version 22, sequences of numbers can be generated using the number-sequence function.

(number-sequence 4)
=> (4)
(number-sequence 1 9)
=> (1 2 3 4 5 6 7 8 9)
(number-sequence 1 16 2)
=> (1 3 5 7 9 11 13 15)

For earlier versions of emacs, here are some small hacks to create a list of integers, in a given range.

Here is a recursive solution:

(defun int-list (x y)
"Returns a list of integers in the range of x and y."
(setq list
(cond ((< x y) (new-int-list y x ())
t (new-int-list x y ())))))
(defun new-int-list (x y list)
(let ((mylist list))
(setq list (add-to-int-list x y list))
(if (equal mylist list)
list
(new-int-list x (- y 1) list))))
(cond ((<= x y)
(append (list y) list))
(t list)))

Here is a more compact recursive sollution:

(defun int-list (x y &rest list)
"Returns a list of integers in the range of x and y."
(let ((i (min x y)) (j (max x y)))
(if (= i j)
(append (list j) (car list))
(int-list i (- j 1) (append (list j) (car list))))))

Here’s a shorter way:

(defun int-list (x y)
(let (list)
(dotimes (i (1+ (- y x)))
(push (+ x i) list))
(nreverse list)))

Here is the same, modified to support y > x:

(defun int-list (i j)
"Returns a list of integers in the range of x and y."
(let ((x (min i j))
(y (max i j)))
(let (list)
(dotimes (i (1+ (- y x)))
(push (+ x i) list))
(nreverse list))))

Lets play golf:

(require 'cl)
(defun int-list (x y)
(loop for i from (min x y) to (max x y) collecting i))

CategoryCode