; File: occur.scm ; Title: search for an atom (symbol,char or number) in a list, any level ;> (occur? 'a '( b c ((a) )d))-> #t ;> (occur? 'a '( b c ((a m) )d)) -> #t ;> (occur? 'a '(( b c m ) d)) -> #f ;search if an element is anywhere (true or false) (define (occur? w L) (cond ((not (pair? L)) #f) ((member w L) #t) (#t (or (occur? w (car L)) (occur? w (cdr L)))) )) ;Number of occurrences of an element in a list- first level ;Ex: >(count-rec 1 '(1 (1 3) 4 1) ) -> 2 (define (count-occur-rec w L) ; how many times x is in L on the first level (cond ((null? L ) 0) ((equal? w (car L )) (+ 1 (count-occur-rec w (cdr L ))) ) (#t (count-occur-rec w (cdr L )) ) )) ;Ex: >(count-iter1 'x '(2 (1 x 3) 4 x) ) -> 1 (define (count-occur-iter w L) ; how many times x is in L on the first level (let ((r 0)) (do ((i L (cdr i))) ((null? i) r) (if (equal? w (car i)) (set! r (+ 1 r))) ) )) ; (count-occur 'a '(a b (b a) a)) -> 3 (define (count-occur w L) ; counts anywhere- how many times it appears (cond ((null? L) 0); L is () ((not (pair? (car L))) ; (car L) is an atom (cond ((equal? w (car L))(+ 1 (count-occur w (cdr L)))) (#t (count-occur w (cdr L))))) (#t (+ (count-occur w (car L)) ; (car L is a list) (count-occur w (cdr L)))) )) ; you obtain same thing if you flatten the list and count on first level