Scheme函数,返回列表中元素出现的第一个位置的索引

时间:2015-04-10 01:12:13

标签: scheme

我的代码的最后一行应该返回列表中出现atm的第一个位置的索引。例如(list-memeber?9'(4 9 3 6 8))应该返回2,但它给我长度+ 1.长度+ 1只应在列表中没有出现atm时起作用。我怎么能这样做?

    (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.

1 个答案:

答案 0 :(得分:0)

所以你要回一个号码。我可以看到几个问题。例如。想象一下,你没有在3元素列表中找到你的元素。它变成了:

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

我想它应该是1而不是'()。此外,如果您在当前元素中找不到atm,每次在第一个元素中找不到所需元素时都会发生(+ 1 (list-length lst)),您执行else并在以后有效地停止搜索结构体。因此,一般情况null?永远不会满足,因为它匹配或不匹配,之后的其他东西永远不会运行。

要整理修复(not (eq? atm (car lst)))案例,并使用谓词{{1}}删除该字词,以使某些工作有效。

相关问题