Toms Lisp List Examples
;; ;; Some small functions to operate on lists. ;; ; Sum of squares. (Okay. No list in this one.) (define (sumsqr x y) (+ (* x x) (* y y))) ; Length of a list. (define (len lis) (if (null? lis) 0 (+ 1 (len (cdr lis)))) ) ; Append lists. (define (app lis1 lis2) (if (null? lis1) lis2 (cons (car lis1) (app (cdr lis1) lis2)) ) ) ; Make each list member a list of itself. (define (addpar lis) (if (null? lis) lis (cons (cons (car lis) ()) (addpar (cdr lis))) ) ) ; Reverse the list. (define (rev lis) (if (null? lis) lis (append (rev (cdr lis)) (cons (car lis) ())) ) ) ; Flatten a list: Remove all sublist structure to make a flat list ; containing the same items. (define (flatten lis) (cond ((null? lis) lis) ((pair? (car lis)) (flatten (append (car lis) (cdr lis)))) (#t (cons (car lis) (flatten (cdr lis)))) ) ) ; Tell if the first item is a member of the list. (define (contains item lis) (cond ((null? lis) nil) ((equal? item (car lis)) #t) (#t (contains item (cdr lis))) ) )