【问题标题】:Checking of list of symbols has the dot symbol?检查符号列表是否有点符号?
【发布时间】:2015-01-15 21:25:56
【问题描述】:

我有一个'(x y . rest) 形式的列表(具有可选参数数量的 lambda 形式)。 我需要检查我是否有这种情况,但我似乎没有检查。我打算做的是搜索. 是否是列表的成员。

> (memq '\. '(x y z . rest))
Exception in memq: improper list (x y z . rest)
Type (debug) to enter the debugger.

> (memq . '(x y z . rest))
Exception: invalid syntax (x y z . rest)
Type (debug) to enter the debugger.

> (memv '\. '(x y z \. rest))
(\x2E; rest) ;this worked but my input is of the form '(x y z . rest) and not '(x y z \. rest)

【问题讨论】:

  • 看看SRFI-1中的不当列表
  • 看看Dot notation in scheme。您真正需要寻找的是链中的最后一个cdr 是空列表还是其他。
  • 当我们谈论 SRFI 1 时,它提供了一个 dotted-list? 谓词,这似乎正是 OP 所寻求的。

标签: scheme


【解决方案1】:

. 符号不是列表的一部分,它只是打印improper list(不以空列表结尾的符号)的约定。要测试我们是否有不正确的列表,请使用内置程序尝试:

(define (atom? x)
  (and (not (null? x))
       (not (pair? x))))

(define (improper-list? lst)
  (or (atom? lst)
      (not (list? lst))))

它按预期工作:

(improper-list? 1)
=> #t
(improper-list? '())
=> #f
(improper-list? '(1 2 3))
=> #f
(improper-list? '(1 2 . x))
=> #t

【讨论】:

  • 我更喜欢我的定义,因为它与不正确列表的 SRFI 1 定义一致,该列表也计算独立原子(长度为 0 的不正确列表)。
  • @ChrisJester-Young 好的,知道了。我相信它现在已经修复了:P
  • 呃,我认为(improper-list? 1) 应该是真的。如果您进行归纳思考,这将是有道理的:不正确的列表是:1. 不是空列表的原子,或 2. cdr 指向不正确列表的对。当您考虑使用 lambda 语法来声明一个接受 1+ 个参数的函数而不是接受 0+ 个参数的函数时,这也是有意义的。
  • @ChrisJester-Young 嗯,我误解了当时的定义:(。现在它已经修复了。
【解决方案2】:

您的列表中没有 . 元素。相反,它是当列表中的最后一个 cdr 不是空列表时使用的符号。不过,这也在其他问题中有所描述。例如,看看Dot notation in scheme

关于检查不正确的列表,其他两个答案是正确的,并且采取了类似的方法。但是,我认为指定一个 proper list 会更简洁一些,它可以更好地定义 proper-list? 然后定义 improper-list ? 就它而言:

(define (proper-list? x)
  ;; a proper list is either the empty list (), or a pair
  ;; whose cdr is a proper list.
  (or (null? x)
      (and (pair? x)
           (proper-list? (cdr x)))))

(define (improper-list? x)
  ;; an improper list is anything that is not a proper list
  (not (proper-list? x)))

【讨论】:

    【解决方案3】:

    (x y z . rest) 列表中没有有一个点符号。这实际上是一个不恰当的列表,以这种方式制作:(cons 'x (cons 'y (cons 'z 'rest)))

    要测试不正确的列表,您可以执行以下操作:

    (define (improper-list? x)
      (cond ((null? x) #f)
            ((pair? x) (improper-list? (cdr x)))
            (else #t)))
    

    【讨论】:

      猜你喜欢
      • 2013-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多