Dr. Racket Recursion count occurrences -
i'm new racket , trying learn it. i'm working through problems i'm struggling with. here problem asking:
write definition recursive function occur takes data expression , list s , returns number of times data expression appears in list s.
example:
(occur '() '(1 () 2 () () 3))
=>3
(occur 1 '(1 2 1 ((3 1)) 4 1))
=> 3 (note looks @ whole elements in list)
(occur '((2)) '(1 ((2)) 3))
=> 1
this have written far:
(define occur (lambda (a s) (cond ((equal? (first s)) (else (occur a(rest s))))))
i'm not sure how implement count. next problem similar , have no idea how approach that. here problem says:
(this similar function above, looks inside sublists well) write recursive function atom-occur?, takes 2 inputs, atom , list s, , outputs boolean true if , if appears somewhere within s, either 1 of data expressions in s, or 1 of data expression in 1 of data expression in s, or…, , on.
example:
(atom-occur? 'a '((x y (p q (a b) r)) z))
=> #t
(atom-occur? 'm '(x (y p (1 (b 4)) z)))
=> #f
any assistance appreciated. thank you.
in racket, standard way solve problem use built-in procedures:
(define occur (lambda (a s) (count (curry equal? a) s)))
but of course, want implement scratch. don't forget base case (empty list), , remember add 1 unit whenever new match found. try this:
(define occur (lambda (a s) (cond ((empty? s) 0) ((equal? (first s)) (add1 (occur (rest s)))) (else (occur (rest s))))))
the second problem similar, uses standard template traversing list of lists, go down on recursion on both first
, rest
of input list, , test equality when we're in atom:
(define atom-occur? (lambda (a s) (cond ((empty? s) #f) ((not (pair? s)) (equal? s)) (else (or (atom-occur? (first s)) (atom-occur? (rest s)))))))
Comments
Post a Comment