## Tuesday, August 25, 2015

### Lisp for the C++ programmer: Function definitions and function calls

Here is the simple Common Lisp example, in which a sum and an ArithmaticMean functions defined. Both C++ and Common Lisp code here calculate the arithmetic mean of 1,2,3,4,5 and 6 which is 3.5. C++ code is commented as in the Common Lisp file.

`````` ; double sum (double *d, int len){
;    double mysum = 0.0;
;    for (int i = 0; i < len; i++){
;        mysum += d[i];
;    }
;    return(mysum);
; }
;
; double ArithmeticMean (double *d, int len){
;    return ( sum(d) / len );
; }

; int main(){
;    double *mylist = (double*) malloc(sizeof(double) * 6);
;    for (int i = 0; i < 6; i++){
;        d[i] = (double)i;
;    }
;    printf("%f\n", ArithmeticMean(d, 6);
;    return(0);
; }

(defun sum (aList)
(setq mysum 0.0)
(dotimes (i (length aList))
(setq mysum (+ mysum (nth i aList )))
)
mysum
)

(defun ArithmeticMean (aList)
(/ (sum aList) (length aList))
)

(print (ArithmeticMean '(1 2 3 4 5 6)))

``````