I need to come up with a scheme function that counts the occurence of an atom within a list. I successfully implemented a simple version but it only works with non-nested lists:
(define (foo x atom)
(cond ((null? x) 0)
((eqv? (car x) atom) (+ 1 (count (cdr x) atom)))
(else (count (cdr x) atom))))
I then attempted a nested-list version of it. However, I recieve the error:
argument of wrong type [car]
(car *whatever variable in list*)
The code is as follows:
(define (foo x atom)
(cond
((null? x) 0)
((not (list? (car x)))
(cond
((eqv? (car x) atom) (+ 1 (foo (cdr x) atom)))
(else (foo (cdr x) atom))))
(else (+ (foo (car x) atom) (foo (cdr x) atom)))))
It fails when I pass aa list such as:
(foo '(1 2 3 1 1 4 1) 1)
Example of count recursively:
(define (count k lst)
(if (null? lst)
0
(if (= k (car lst))
(+ 1 (count k (cdr lst)))
(count k (cdr lst)))))
(count 2 '(2 3 4 4 4 5 5 3 2))
> 2
(count 4 '(2 3 4 4 4 5 5 3 2))
> 4
Explanation: if k exists in car (first), add 1 and check cdr (rest)...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.