It has been a while since I did much LISP but here are some things that may help you improve your program.
Avoid using keywords as variable names
list is a function and shouldn't be overloaded as a variable name. You might use
mylist to make it clear that it's a variable and not the function.
LISP tends to reward the use of compositions of small functions. Instead of large functions that do multiple things, try instead to create small functions that each do one thing and then compose them. For example:
(defun average (mylist)
(/ (apply #'+ mylist) (length mylist)))
mapchar instead of
If you are using
progn on a regular basis, it's probably a symptom that you're trying to write LISP using a procedural style. Remember that a list is a fundamental concept in LISP, so there are usually ways to do things with lists without either creating new variables or using
progn. For example, let's consider what you're trying to do here. First, you want to remove negative numbers from the list:
(defun remove-neg (mylist)
(remove-if 'minusp mylist))
Next, we want to "peg" numbers at 100. That is, convert anything greater than 100 into 100:
(defun peg-100 (mylist)
(mapcar #'(lambda (x) (min x 100)) mylist))
mapcar function just applies the given function to each item in the list. We create a lambda to express that function, but it could also have been made into a separate function.
The average function was already shown above, so all that's left is to compute the skewed average:
(defun skewed-avg (mylist)
(average (peg-100 (remove-neg mylist))))
This is likely to perform more slowly than your versions because this version makes multiple passes through the list, but it's more LISPy and if performance becomes a problem, it can often be addressed by using
condition to handle errors
Error handling in LISP is not unlike exception handling in Java, C++ or Python. It's not complex and is quite flexible. You can read about it in this chapter of an online book. Essentially you define an error
condition and then use a
handler-case to direct the
error to the appropriate handler.