Subject: Re: random-list function
From: Erik Naggum <erik@naggum.net>
Date: 2000/10/02
Newsgroups: comp.lang.lisp
Message-ID: <3179472571310961@naggum.net>
* NS <kalloni2000@aol.com>
| So far, a couple of very cool Lisp programmers from this news group
| showed me much more efficient ways to do it (and I also would like
| to acknowledge them here). I would like to see more coding "styles"
| from the Lisp gurus out there. This will help my learning a lot.
It might also help your learning process to explain why you did what
you did. For instance, why pre-allocate the list, then fill it?
Why use a recursive helper function to traverse (create) a list?
Why name your variable "lst"? (Some of these indicate a Scheme
background, specifically one that tried to highlight difference
between Scheme and "all other" languages, but which failed to
communicate that you can write more "normal" code in Scheme, too.)
As long as you want recursion, here's one for educational purposes:
(defun random-list (length range)
(if (plusp length)
(cons (random range) (random-list (1- length) range))
nil))
It might help your learning process to explain why this is insane for
production purposes.
You can solve the problem in many different ways, obviously, but I
favor those that require a minimum of my own code, i.e., that use
the rich language that is Common Lisp to its fullest, hoping for (or
counting on) very efficient, error-free implementations of the
functions specified in the language.
(mapcar #'random (make-list length :initial-element range))
If you don't intend to call random-list a lot or with huge values of
length, you won't notice the double space requirements of this one.
Incidentally, your version with "fill" is very similar to what
Common Lisp calls "map-into", which saves on the space usage:
(let ((list (make-list length :initial-element range)))
(map-into list #'random list))
#:Erik
--
If this is not what you expected, please alter your expectations.