gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 18:51:41 25 4
gpt4 key购买 nike

我正在尝试编写一个函数 (positions N A L),它返回 A 出现在 L 中的每个索引的列表,N 是赋予 L 的第一个元素的数字。

例如,

(位置 0 'a '(a b c a d e a)) => (0 3 6)

(位置 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?,这是最通用的相等比较,适用于许多数据类型(数字、符号、 bool 值等)。此外,对最后一个条件使用 else ,使用 #t 是 Common Lisp 约定,不适用于 Scheme。

关于functional-programming - 创建元素出现在列表中的所有索引列表的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35630403/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com