Hi,
I am not an English native, so, if you see any fault or incoherence, please correct me.
I'm currently learning SCHEME language, and our teacher told us to create two programs: one which counts the number of occurrence of an element in a list, and the other which verifies if the element is present or not.
The first program works for simple list, but for the lists with imbrication, it seems like it doesn't count all the element (the one inside the imbrication). For the second, I think it's a similar problem.
Here is what I have done for the first one:
(define occur (lambda (x L)
(cond
((null? L) 0)
((eq? x (car L)) (+ 1 (occur x (cdr L))))
(#t (occur x (cdr L)))
)))
Ok, I don't have any idea what happened with your cdr examples, but the problem in your functions is that you are iterating through all the elements in the list and comparing them with x but 'a is not an element of the first list. The first list has only two elements: the symbol 'b and the list '(a b). If you want to look at the elements of sublists then you will need to traverse them explicitly or flatten the list first.
#lang racket
;; count the number of times that 'x' occurs in the s-expression L
(define occur2 (lambda (x L)
(cond
[(pair? L) (+ (occur2 x (car L)) (occur2 x (cdr L)))]
[else (cond [(equal? x L) 1]
[else 0])])))
(require rackunit)
(check-equal? (occur2 'a '(a (b a) a (b b (a) b))) 4)
It's true that the inner cond can be flattened, but this one clearly adheres to the s-expression template, so it reads more nicely to me. I also like the "one-or-zero" clarity of the inner cond.
It's simpler than mine, but my professor told us to use only the basic function of Scheme while we're still at the beginner level. So no 'if' or 'else', etc., but I will keep this one as another solution.