This is a Lisp page, written Sat Jan 19 15:21:54 PST 2008.
LISP functions can accept any number of arguments after the "&rest" keyword. So, to add up any number of "nums":
(defun sum (&rest nums)
(let ((sum 0))
(dolist (one nums sum)
(incf sum one))))
E.g.
(SUM 1 1 1 1 2 2 4 100) => 112
And, if you want the mean value, divide the sum by the number of items in the list:
(defun mean (&rest nums)
(let ((sum 0)
(n 0))
(dolist (one nums (/ sum n))
(incf n)
(incf sum one))))
E.g.
(MEAN 1 1 1 1 2 2 4 100) => 14
LISP functions can also return more than one value using the "values" keyword. Here, we compute mean and standard deviation of a set of numbers.
(defun mean-sd (&rest nums)
(let ((sum 0)
(n 0)
(sumSq 0))
(labels ((mean () (/ sum n))
(sd () (sqrt (/ (- sumSq(/ (* sum sum) n)) (- n 1) ))))
(dolist (one nums)
(incf n)
(incf sum one)
(incf sumSq (* one one)))
(values
(mean)
(sd)))))
E.g.
(MEAN-sd 1 1 1 1 2 2 4 100) => 14 34.764515
We can use the same kind of function to return the median and the "spread" of a set of numbers. The median value is the point at which half the values lie below it:
This list also returns "spread", i.e. the difference between the 50% and 75% value. "Spread" (not the official technical name) is useful for measuring the expected deviation from the median.
(defun median (&rest nums)
"return 50% and (75-50)% values"
(let* ((n1 (sort nums #'<))
(l (length n1))
(mid (floor (/ l 2)))
(midval (nth mid n1))
(75percent (nth (floor (* l 0.75)) n1))
(50percent (if (oddp l)
midval
(mean midval (nth (- mid 1) n1)))))
(values
50percent
(- 75percent
50percent))))
E.g.
(MEDIAN 1 1 1 1 2 2 4 100) => 3/2 5/2