从与我的方案中的字符匹配的列表中过滤单词 [英] Filtering words from a list that matches my char in scheme
问题描述
我刚开始学习scheme.我需要创建一个谓词函数来过滤一个列表(可能是空的)并且只在它们与字符匹配时才输出:
I just started to learn scheme. I need to create a predicate function that will filter a list(maybe empty) and only output if they match with a char:
(filter-word '((#\g #\a #\m #\e)
(#\d #\o #\l #\l)
(#\d #\i #\c #\e))
#\a)
输出:
((#\g #\a #\m #\e))
我正在尝试使用过滤器和成员,但我不知道如何构造此函数,也不知道是否可以一起使用过滤器 lambda 和成员.对于这种情况,Map 是更好的选择吗?
I'm trying to use filter and member, but I don't know how to structure this function, and I don't know if is possible to use filter lambda and member altogether. Is Map a better option for this case?
(define (filter-word words ch)
(cond
[(null? words) words]
[(filter
(λ (words)(member? ch (words)) words))]))
我知道不完整,但在这种情况下,输出是 #<procedure:...
I know is incomplete but in this case, the output is #<procedure:...
推荐答案
你可以直接使用 filter
,不需要额外的case.这应该有效:
You can use filter
directly, there's no need for an extra case. This should work:
(define (filter-word words ch)
(filter (lambda (word) (member ch word))
words))
例如:
(filter-word '((#\b #\u #\s)
(#\b #\a #\r)
(#\c #\a #\r))
'#\b)
=> '((#\b #\u #\s) (#\b #\a #\r))
(filter-word '((#\b #\u #\s)
(#\b #\a #\r)
(#\c #\a #\r))
'#\c)
=> '((#\c #\a #\r))
这篇关于从与我的方案中的字符匹配的列表中过滤单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!