【问题标题】:Filtering words from a list that matches my char in scheme从与我的字符匹配的列表中过滤单词
【发布时间】:2021-06-17 22:41:05
【问题描述】:

我刚开始学习方案。 我需要创建一个谓词函数来过滤列表(可能为空),并且仅在它们与字符匹配时才输出:

(filter-word '((#\g #\a #\m #\e)
               (#\d #\o #\l #\l)
               (#\d #\i #\c #\e))
              #\a)

输出:

((#\g #\a #\m #\e))

我正在尝试使用过滤器和成员,但我不知道如何构造这个函数,我不知道是否可以同时使用过滤器 lambda 和成员。 在这种情况下,地图是更好的选择吗?

(define (filter-word words ch)
  (cond
    [(null? words) words]
    [(filter
     (λ (words)(member? ch (words)) words))]))
     

我知道不完整,但在这种情况下,输出是 #<...>

    标签: scheme racket


    【解决方案1】:

    您可以直接使用filter,不需要额外的案例。这应该有效:

    (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))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-19
      • 1970-01-01
      • 1970-01-01
      • 2014-02-22
      • 1970-01-01
      • 1970-01-01
      • 2015-10-14
      相关资源
      最近更新 更多