CSC 330 Lecture Notes Week 8
Introduction to Functional Programming and Lisp
(defun APlusB (a b)
(+ a b)
)
int APlusB(int a,b) {
return a + b;
}
| Lisp Form | PCJ Form | Remarks |
| (+ a b) | a + b | Call the built-in addition function |
| (APlusB 10 20) | APlusB(10, 20) | Call the user-defined function APlusB |
(cond ( (test-expression1) (expression11) ... (expression1j) ) )
. . .
( (test-expressionn) (expressionn1) ... (expressionnk) )
| Operation | Meaning |
| car | return the first element of a list |
| cdr | return everything except the first element of a list |
| cons | construct a new list, given an atom and another list |
(defun f (x) ... ) (defun a (x) ...)
(f (a b))
(f '(a b))
(defun avg (l)
(/ (sum l) (length l))
)
(defun sum (l)
(cond ((null l) 0)
(t (+ (car l) (sum (cdr l))))
)
)
(defun main ()
(avg '(1 2 3 4 5))
)
int avg(int l[], int length) {
int i, sum;
for (i=0, sum=0; i<length; i++)
sum += l[i];
return sum/length;
}
main() {
int l[] = {1,2,3,4,5};
printf("%d\n", avg(l, 5));
}
int sum(list l) {
if (null(l)) /* if the list l is empty */
return 0; /* then return 0 as the summing result */
else /* otherwise, */
return car(l) + /* return the sum of the 1st list element plus */
sum(cdr(l); /* the sum of the rest of the elements */
(defun my-nth (n l)
(cond ( (< n 0) nil )
( (eq n 0) (car l) )
( t (my-nth (- n 1) (cdr l)) )
)
)