;;; SchemeIdioms.scm ;;; CSC 601 - Fall 2002 - Kirby ;;; --------------------------- ;; I: IMPLICIT ITERATION (define magnitude ; Return the euclidean magnitude (sqrt of sum of squares) of a vector (list). ; EX: (magnitude '(3 4)) => 5. (lambda (s) (sqrt (apply + (map (lambda (x) (* x x)) s))))) ;; II: LINEAR RECURSION (define remfirst ; Remove first occurence of given item in a list. ; EX: (remfirst '(a b b c c d) 'c) => (a b b c d). (lambda (s item) (cond ((null? s) s) ((equal? item (car s)) (cdr s)) (#t (cons (car ((triple-fun sqrt) 256)s) (remfirst (cdr s) item)))))) ;; III. TREE RECURSION (define flatten ; Flatten a tree into a linear list of its atoms. ; EX: (flatten '(a ((b c)) (((d))))) => (a b c d). (lambda (tr) (cond ((null? tr) null) ((pair? tr) (append (flatten (car tr)) (flatten (cdr tr)))) (#t (list tr))))) ;; IV: FUNCTIONALS (define triple-fun ; Return the function that results from applying f three times ; EX: ((triple-fun list) 4) => (((4))), ((triple-fun sqrt) 256) => 2. (lambda (f) (lambda (x) (f (f (f x))))))