Auotolisp Make List

This function is derived from the Common Lisp make-list function.

A further spinoff of this function is to generate a new list by repeating an existing list. This is called make-list-from and uses a similar argument list, except that the initial-element argument is replaced by an initial-list argument.

# Code

Simplistic version

```
(defun make-list (size initial-element / lst)
(repeat size (setq lst (cons initial-element lst)))
lst)
(defun make-list-from (size initial-list / lst)
(cond ((= size (length initial-list)) initial-list)
((< size (length initial-list))
(setq lst (reverse initial-list))
(repeat (- (length initial-list) size) (setq lst (cdr lst)))
(reverse lst))
((setq lst initial-list)
(while (< (length lst) (- size (length initial-list))) (setq lst (append initial-list lst)))
(append lst (make-list-from (- size (length lst)) initial-list)))))
```

Modified version to optimize speed for longer lists. Help from bruno_vdh [1] for simplifying this without loosing too much speed.

```
(defun make-list (size initial-element / lst)
(if (> size 0)
(progn (setq lst (list initial-element))
(while (< (* (length lst) 2) size) (setq lst (append lst lst)))
(append lst (make-list (- size (length lst)) initial-element)))))
(defun make-list-from (size initial-list / x)
(cond ((>= size (length initial-list))
(setq x initial-list)
(while (< (* (length x) 2) size) (setq x (append x x)))
(append x (make-list-from (- size (length x)) initial-list)))
((> n 0)
(setq initial-list (reverse initial-list))
(repeat (/ (- (length initial-list) size) 4) (setq initial-list (cddddr initial-list)))
(repeat (rem (- (length initial-list) size) 4) (setq initial-list (cdr initial-list)))
(reverse initial-list))))
```

An even more optimized [2] version for long lists

```
(defun make-list-from (size initial-list / r)
(if (= size (length initial-list))
initial-list
(progn
(setq r (list (mapcar '(lambda (x y) x) initial-list (repeat (rem size (length initial-list)) (setq r (cons 1 r))))))
(if (< size (length initial-list))
(car r)
(apply 'append (repeat (/ size (length initial-list)) (setq r (cons initial-list r))))))))
```

Bibliography

2. Derived from code posted by Stefan here: http://www.theswamp.org/index.php?topic=42091.msg472909#msg472909

page revision: 3, last edited: 02 Jul 2012 10:47