// Scheme is for wimps. Tough guys use C #include #include // claim: anything you can do in scheme I can do in C at least as well #define nil 0 // null, empty list typedef struct node* list; struct node { int item; // forget the untyped part for now... list next; }; list cons(int i, list n) { list newnode = (list)malloc(sizeof(struct node)); newnode->item =i; newnode->next =n; } int car(list n) { return n->item; } list cdr(list n) { return n->next; } // calculate length of list, tail-recursively: int length(list n) { int ilen(list n, int cx) { if (n==nil) return cx; else return ilen(cdr(n),1+cx); } return ilen(n,0); } // calculate product of list, tail-recursively int product(list m, int ax) // ax should be 1 initially { if (m==nil) return ax; else product(cdr(m), car(m)*ax); } //(define (product m ax) (if (null? m) ax (product (cdr m) (* (car m) ax)))) //(define (prod m) (if (null? m) 1 (* (car m) (product (cdr m))))) list map(list m, int (*f) (int)) { if (m==nil) return nil; else return cons(f(car(m)), map(cdr(m),f)); } void printlist(list m) { for(;m!=nil;m=cdr(m)) printf("%d ",car(m)); printf("\n"); } int howmany(list m, int (*p)(int)) { int cx = 0; //counter for(;m!=nil;m=cdr(m)) if (p(car(m))) cx++; return cx; } //(define (howmany m p cx) (if (null? m) cx (if (p (car m)) (howmany (cdr m) p (+ cx 1)) (howmany (cdr m) p cx)))) int forall(list m, int (*p)(int)) { return (m==nil || p(car(m)) && forall(cdr(m),p)); } // (define (forall m p) (or (null? m) (and (p (car m)) (forall (cdr m) p)))) int exists(list m, int (*p)(int)) { int notp(int x) { return !p(x); } return !forall(m,¬p); } //(define (exists m p) (not (forall m (lambda (x) (not (p x)))))) // memory management void deallocate(list m) { if (m!=nil) deallocate(cdr(m)); free(m); } void iterdealloc(list m) { while (m!=nil) { list tmp = m; m = cdr(m); free(tmp); } } int main() { int cube(int x) {return x*x*x;} int odd(int x) { return x%2==1; } list m = cons(2,cons(3,cons(5,cons(7,nil)))); printf("length %d, product %d\n", length(m),product(m,1)); m = map(m,&cube); printlist(m); printf("%d\n",howmany(m,&odd)); printf("%d\n",exists(m,&odd)); list A = cons(3,cons(5,cons(7,cons(10,nil)))); list B = cons(1,cdr(A)); // what is B? 1 5 7? printlist(B); list tmp = A; // for memory management A = map(A,&odd); printlist(A); // prints 1 1 1 0 (1=true, 0=false) deallocate(tmp); // free memory for previous A printlist(B); //??? return 0; }