【问题标题】:How can I get a list up until the last occurrence of an element from a list?如何在列表中最后一次出现元素之前获取列表?
【发布时间】:2014-04-16 02:28:16
【问题描述】:

我正在使用方案 R5RS。

给定一个包含多个条目的列表,我想返回该列表直到给定元素的最后一次出现。

所以对于以下输入:

列表'("hi" "how" "are" "you")
关键字"you"

我想要以下输出:
列表'("hi" "how" "are")

我在 R5RS 方案中找不到具有此功能的功能,但也许我遗漏了一些东西。如果没有这样的功能,我该如何实现呢?

【问题讨论】:

    标签: scheme r5rs


    【解决方案1】:

    这比乍一看要复杂一些,但这应该可以:

    (define (last lst key)
      (cond ((null? lst) '())
            ((member key (cdr lst))
             (cons (car lst) (last (cdr lst) key)))
            (else '())))
    

    关键的见解是您应该使用member 来检查该元素是否仍然存在于列表中(这将告诉我们何时找到它的最后一次出现)。您还应该考虑两种特殊情况 - 如果列表为空,或者键不在列表中,会发生什么情况?在这两种情况下,我都会返回一个空列表。例如:

    (last '("hi" "how" "are" "you") "you")
    => '("hi" "how" "are")
    
    (last '("hi" "how" "are" "how" "you") "how")
    => '("hi" "how" "are")
    
    (last '("hi" "how" "are" "how" "you") "today")
    => '()
    
    (last '() "empty")
    => '()
    

    【讨论】:

    • 太棒了!这是我的荣幸:)
    【解决方案2】:

    如果您反转列表然后查找 first 出现,这可以非常简洁地完成:

    (define (last lst key)
      (define r (member key (reverse lst)))
      (if r 
          (reverse (cdr r))
          '()))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-10
      • 2010-10-30
      • 2022-11-15
      • 2015-12-12
      • 2016-03-01
      • 2018-08-25
      • 2015-04-24
      相关资源
      最近更新 更多