我正在尝试编写一个函数(positions N A L)
,该函数返回A出现在L中的每个索引的列表,而N是赋予L的第一个元素的数字。
例如,
(positions 0 'a '(a b c a d e a))
=> (0 3 6)
(positions 1 'a '(a b c a d e a))
=> (1 4 7)
到目前为止,我想出了这个(不能正常工作):
(define (positions N A L)
(cond
((null? L)
'())
((= (car L) A)
(cons N (positions (+ N 1) A (cdr L))))
(#t
(positions (+ N 1) A (cdr L)))))
尝试这个:
(define (positions N A L)
(cond
((null? L) '())
((equal? (car L) A) (cons N (positions (+ N 1) A (cdr L))))
(else (positions (+ N 1) A (cdr L)))))
问题是=
只为数字定义。如果您确定列表仅包含符号,请使用eq?
。否则,使用equal?
,这是最通用的相等性比较,并且适用于许多数据类型(数字,符号,布尔值等)。另外,else
用于最后一个条件时,使用的#t
是Common Lisp约定,不适用于Scheme。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句