我有一个元素列表 '(a b c),我想找出其中是否包含(true或false)x,其中x可以是'a或'd,是否有内置函数可实现此功能?
memq
、memv
或member
,具体取决于您想要使用eq?
、eqv?
或equal?
来查找相等性。> (memq 'a '(a b c))
'(a b c)
> (memq 'b '(a b c))
'(b c)
> (memq 'x '(a b c))
#f
#f
和未找到要查找的元素的情况。列表是一个真值(Scheme中唯一的假值是#f
),因此您可以在任何期望布尔值的上下文中使用memq
、memv
或member
的结果,例如if
、cond
、and
或or
表达式。> (if (memq 'a '(a b c))
"It's there! :)"
"It's not... :(")
"It's there! :)"
> (eq? 'a 'a)
#t
> (eq? 'a 'b)
#f
> (eq? (list 'a 'b 'c) (list 'a 'b 'c))
#f
> (equal? (list 'a 'b 'c) (list 'a 'b 'c))
#t
> (eqv? (+ 1/2 1/3) (+ 1/2 1/3))
#t
find
或 find-tail
。> (find-tail? (lambda (x) (> x 3)) '(1 2 3 4 5 6))
'(4 5 6)
memq
函数的名称是什么意思? - Freewindmemq
是 member
函数族中的一个,它根据某种等价关系(与其他函数一样,如 member
和 memv
)在列表中查找项目。q
、v
或全名将其与它们各自使用的三个等价函数连接起来;memq
使用 eq?
来测试等价性,memv
使用 eqv?
来测试等价性,而 member
使用 equal?
来测试等价性。有关它们之间的区别,请参见等价函数的链接文档。 - Brian Campbellmemq
可以被看作是 mem-q
,而 memv
可以被看作是 mem-v
。 - Freewind> (cond ((member 'a '(a b c)) '#t) (else '#f))
#t
> (cond ((member 'd '(a b c)) '#t) (else '#f))
#f
member从元素开始返回所有内容,或者返回#f。使用cond将其转换为真或假。
#t
可以替换为 '#t
。 - Iulius Curt我不知道是否有内置函数,但您可以创建一个:
(define (occurrence x lst)
(if (null? lst) 0
(if (equal? x (car lst)) (+ 1 (occurrence x (cdr lst)))
(occurrence x (cdr lst))
)
)
)
x
出现的次数。你还可以用 true
或者 false
来扩展它。你正在寻找“find”
基础知识 - 最简单的情况就是(find Entry List),通常用作谓词:“Entry是否在List中?”如果成功找到所需元素,则返回第一个匹配元素,而不仅仅是“t”。(摘自第二个链接。)
http://www.cs.cmu.edu/Groups/AI/html/cltl/clm/node145.html
-或-
(define (member? x list)
(cond ((null? list) #f)
((equal? x (car list)) #t)
(else (member? x (cdr list)))))
(member? 10 '(4 2 3))
输出为 #f