创建元素出现在列表中的所有索引列表的函数

Function that creates a list of all indexes where an element appears in a list

我正在尝试编写一个函数 (positions N A L),其中 returns 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是不适用于 Scheme 的 Common Lisp 约定。