简体   繁体   English

两元素列表方案

[英]Two Element List Scheme

I need to write a function that determines if the given list is a pair of elements. 我需要编写一个确定给定列表是否为一对元素的函数。 The program will simply respond #t if the list contains exactly two elements or #f if it does not, such that: 如果列表恰好包含两个元素,则程序将仅响应#t;否则,将仅响应#f,例如:

(zipper? '((a 1)(b 2))) => #t

and

(zipper? '((foo 100)(bar 2 3))) => #f

I'm still fairly new to Scheme so any help would be much appreciated! 我对Scheme还是很陌生,因此不胜感激! Thanks! 谢谢!

It isn't clear if the "correct" input for the procedure is an arbitrary list or a two-element list. 尚不清楚该过程的“正确”输入是任意列表还是两元素列表。 If it's strictly a two-element list, this will work: 如果严格来说是两个元素的列表,它将起作用:

(define (is-two-element-list? lst)
  (and (list? lst)
       (= (length lst) 2)))

(define (zipper? lst)
  (and (is-two-element-list? lst)
       (is-two-element-list? (first lst))
       (is-two-element-list? (second lst))))

… And if it's an arbitrary-length list whose elements we want to check, this will work in Racket, using andmap : …如果这是一个任意长度的列表,我们要检查其元素,则可以使用andmap在Racket中运行:

(define (zipper? lst)
  (andmap is-two-element-list? lst))

If you are not using Racket, then this solution using every will work in any interpreter with SRFIs: 如果您不使用Racket,那么使用every此解决方案将在具有SRFI的任何解释器中运行:

(require srfi/1)

(define (zipper? lst)
  (every is-two-element-list? lst))

Either way, notice that the trick was defining the is-two-element-list? 无论哪种方式,请注意,诀窍是定义is-two-element-list? procedure, which verifies the two-element-list property, after that we can apply it as needed. 验证两个元素列表属性的过程,之后我们可以根据需要应用它。

Think of it this way. 这样想吧。 If the zipper list is '() then the answer is #t . 如果zipper列表为'()则答案为#t If the zipper list is not '() then if the first element is two elements and the rest is another zipper? 如果zipper列表不是'()那么第一个元素是两个元素,其余元素是另一个zipper? , then return #t . ,然后返回#t

(define (zipper? list)
  (or (null? list)
      (and (= 2 (length (car list)))
           (zipper? (cdr list)))))

or maybe you mean: 也许你的意思是:

(define (zipper? list)
  (or (not (pair? list))
      (and (= 2 (length list))
           (zipper? (list-ref list 0))
           (zipper? (list-ref list 1)))))

every element, at any level, has two elements. 每个元素在任何级别都有两个元素。

> (zipper? '((a 1 2) '(b)))
#f
> (zipper? '(a b))
#t
> (zipper? '(((a (b b)) c) (1 2)))
#t

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM