I am new to scheme and have been given this problem as homework. I don't know how to keep a running count in scheme, and that's the part I need help with.
Here's the problem again:
Function count should accept two arguments: an atom and a simple list. The function should return the number of times the atom is found in the list.
Here's what I have so far:
(define (count atm lst)
(cond
((null? lst) 0)
((eq? atm (car lst)) (i don't know how to make a count) (count atm (cdr lst)))
(else (count atm (cdr lst)))))
Any help would be very appreciated!
I still don't understand what needs to happen to increment the number of times开发者_StackOverflow the atom is found in the list for each iteration of the function.
This is the test case my teacher gave me: (count 'john '(john paul george ringo))
which should return 2.
I've been staring at this problem long enough, please explain how to make the count work.
You, my friend, are very very close to the answer to this problem. To finish the problem, you need to write a test case. The reason you need to write a test case is that you can then think concretely about what the pieces of your code mean. Most specifically, you need to think about what (count atm (cdr lst))
evaluates to for the particular input that you're thinking of, and then think about what the correct answer is, and how they're related.
Let's look at your code.
(define (count atm lst)
(cond
;; This is obviously correct
((null? lst) 0)
;; See below
((eq? atm (car lst)) (somefunction (count atm (cdr lst))))
;; The next one's find as well
(else (count atm (cdr lst)))))
If the tail (cdr
) of lst
contains n
occurrences of atm
, (count atm (cdr lst))
should return n
. Then, knowing n
, if (car lst)
is eq?
to atm
, how many are there in lst
?
(define (count-atom atm list)
(cond((null? list) 0)
((eq? atm (car list)) (+ 1 (count-atom atm (cdr list))))
(else (count-atom atm (cdr list)))
)
)
(count-atom 'a '(a b a b a r a a a a a a a a a))
精彩评论