Scheme function that returns the index of the first location where an element occurs in the list -


this question has answer here:

the last line of code should returns index of first location atm occurs in list. example (list-memeber? 9 '(4 9 3 6 8)) should return 2, gives me length + 1. length + 1 should work when atm doesn't occur in list. how 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 empty (this part works fine)        ((not (eq? atm (car lst))) (+ 1 (list-length lst))) ;if atm not occur in list, function returns length + 1 ((this works fine)        ((eq? atm (car lst)) 1) ;if fisrt element equals atm, function returns location 1 (this works fine)        (else (+ 1 (list-memeber? atm (cdr lst)))))) ;here i'm having problem. should return location of index atm occurs. 

so returning number. can see several problems. eg. imagine don't find element in 3 element list.. turns into:

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

i guess should 1 instead of '(). further, if in current element don't find atm, happens every time desired element not found in first element, (+ 1 (list-length lst)) , stop searching later in structure. general case else never met since either matches or doesn't , else after never run.

to round fix null? case , remove term predicate (not (eq? atm (car lst))) working.


Popular posts from this blog