-1

The last line of my code should returns the index of the first location where atm occurs in the list. for example (list-memeber? 9 '(4 9 3 6 8)) should return 2, but it gives me length + 1. Length + 1 should only work when atm doesn't occur in the list. How could I do that?

    (define (list-length l)
       (if (null? l)
         0
       (+ 1 (list-length (cdr l)))))

    (define (list-memeber? atm lst)
       (cond
       ((null? lst) '() ) ;returns null if list is empty (This part works fine)
       ((not (eq? atm (car lst))) (+ 1 (list-length lst))) ;If atm does not occur in the list, the function returns length + 1 ((This works fine)
       ((eq? atm (car lst)) 1) ;if fisrt element equals atm, function returns location which is 1 (This also works fine)
       (else (+ 1 (list-memeber? atm (cdr lst)))))) ;here is where I'm having problem. This should return location of index where atm occurs.
joe
  • 33
  • 5

1 Answers1

0

So you are returning a number. I can see several problems. Eg. Imagine you don't find your element in a 3 element list.. It turns into:

(+ 1 (+ 1 (+ 1 '()))) ; this part does not work fine!

I guess it should be 1 instead of '(). Further, if you in the current element don't find atm, which happens every time the desired element is not found in the very first element, you do (+ 1 (list-length lst)) and effectively stop searching for it later in the structure. Thus the general case else is never met since either it matches or it doesn't and a else after that would never be run.

To round it up fix null? case and remove the term with the predicate (not (eq? atm (car lst))) to get something working.

Sylwester
  • 47,942
  • 4
  • 47
  • 79