CSC 530 Lecture Notes Week 1
Introduction to the Course
Introduction to Lisp
(current state, symbol read, new state, symbol written, move direction)
(0, ,1,1,R) (1, ,2,1,R) (2, ,3,1,R) (3, ,4,1,R)
(0,1,1,X,R) (0,,,0,,,R) (0,:,3,:,R) (1,1,1,1,R) (1,,, 1,,,R) (1,:, 1,:,R) (1, , 2,1,L) (2,1,2,1,L) (2,:,2,:,L) (2,,,2,:,L) (2,X,0,X,R)
11,111: ^ 0
XX,XXX:11111 ^ 3
State | Description |
0 | check for 1, ',', or ':' and goto state 1, 0, or 3, resp; if a 1, replace it with a 'X' to indicate that it's been handled as an operand |
1 | carry a 1 over to the far right end of the tape and write it |
2 | go back to the rightmost X to get the next 1 |
3 | halt |
f(x0,...,xn) = h(g0(x0,...,xn),...,gk(x0,...,xn))
where g and h are defined recursively 2f(0,x1,...,xn) = g(x1,...,xn) f(S(n),x1,...,xn) = h(f(x1,...,xn),n,x1,...,xn)
Four(x) = S(S(S(S(Z(x)))))
Add(0,y) = y Add(S(n),y) = S(Add(n,y))
If the advantages of applicative languages are so compelling, why is their use not more widespread?
IHaving introduced the basic historical concepts, we now proceed to
examine
applicative languages in detail, beginning with Pure Lisp.
(defun APlusB (a b) (+ a b) )
int APlusB(int a,b) { return a + b; }
Lisp Form | CJ 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("%d0, 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 */ sum(cdr(l); /* with 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)) ) ) )
4 It's named "my-nth" since "nth" is built-in to Lisp, and we don't want to change its definition.