(define (occurs? item tree)
(if (pair? tree)
(or (occurs? item (car tree))
(occurs? item (cdr tree)))
(eqv? item tree) ) )
(member 'math '(cs physics math chemistry))
=> (math chemistry)
Since this is not #f, it is logically true: math is
a member of the list.
(assoc 'bread '((eggs .69) (milk 1.89) (bread 1.39)))
=> (bread 1.39)
Remember to use cadr if what you want is the price of the item.
(+ item sum)If this is the return value of the function, fine; but if you want to add to sum, you must use set!:
(set! sum (+ item sum))
Suppose we want to count the number of symbols is a list:
Wrong: (define (nsymbols lst)
(let ((n 0))
(if (pair? lst)
(begin
(if (symbol? (car lst))
(set! n (+ n 1)) ) )
(nsymbols (cdr lst)) )
n))
This function doesn't work. The author is expecting the recursive call
to nsymbols to increment n for the rest of the list,
but what it does is to increment a new copy of n, which
then is lost. There is a disconnect between the function and its
recursive calls, and the value gets dropped.
We can use the value of the recursive call to hold the value of n on the way back:
Right: (define (nsymbols lst)
(if (pair? lst)
(if (symbol? (car lst))
(+ 1 (nsymbols (cdr lst)))
(nsymbols (cdr lst)))
0))
We can use tail recursion and send the value of n down:
Right: (define (nsymbols lst) (nsymbolsb lst 0))
(define (nsymbolsb lst n)
(if (pair? lst)
(nsymbolsb (cdr lst)
(+ n (if (symbol? (car lst))
1
0)))
n))
We can use iteration, so there is only one value of n:
Right: (define (nsymbols lst)
(let ((n 0))
(dolist (item lst)
(if (symbol? item)
(set! n (+ n 1)) ) )
n ))
(set! n (+ n 1)) (myfunction n)with the simpler code:
(myfunction (+ n 1))