0 Replies - 1174 Views - Last Post: 02 June 2011 - 03:39 PM

#1 I X Code X 1  Icon User is offline

  • D.I.C Head
  • member icon

Reputation: 47
  • View blog
  • Posts: 66
  • Joined: 28-July 10

[Lisp] Common Lisp - Find Average

Posted 02 June 2011 - 03:39 PM

Description: Should work in an Common Lisp implementation; I use Clisp.In Common Lisp it can sometimes hard to give the program the parameters you really want due to it being so geared towards lists. Unless of course you're into that kind of stuff. This snippet will look at the &rest parameter. You'll find it can be quite useful.
(defun find-average (n &rest m)
	(let ((x (length m))) 
	    (let ((l (apply '+ m))) 
		(float (/ (+ n l) (1+ x))))))


; In line number 1 the parameter m is declared as a &rest parameter. This
; means that m can take an arbitrary number of arguments and they are all 
; passed into a list.

; Next we simply find the length of m,(the list we just created), which we, 
; set to x, and add all the elements in the list up using Common Lisp's 
; apply function, which we set to l.

; Finally, all we have to do is add one to x (to include our first parameter,
; add our first parameter to our total, n, and then divide by x. We use float
; so that our number is never printed as a ratio.

; This is done in a purely functional way and works efficiently for a 
; seemingly huge amount of numbers.

(find-average 1 2 3 4)

2.5

; If we did not use the &rest parameter this function would have to be 
; called as such: (find-average '(1 2 3 4))
; That way is farther from the human way of reading.


(find-average 1 8868 2 929 8 39 100 388 18 18 8 81 30 8 3 4)

656.5625




Is This A Good Question/Topic? 0
  • +

Page 1 of 1