【问题标题】:Comparing individual elements of two lists of the same length in DrRacket在 DrRacket 中比较两个相同长度列表的单个元素
【发布时间】:2014-02-23 15:41:31
【问题描述】:

我正在尝试编写一个函数,该函数接受两个列表(必须等长),然后遍历每个列表来比较各个项目。

例如:(1 2 3)(2 4 5) 将返回 true,因为列表 2 的每个元素都大于列表 1 中的相应元素。(1 2 3)(0 4 1) 将返回 false(1 2 3)(1 2 3 4) 因为它们的大小不同。使用 Dr Racket

(define (each-bigger? a-lon another-lon)
  (cond
    (if
    [(= (length a-lon) (length another-lon))true]
    (then
    [(> (first a-lon) (first another-lon))true]
    (then
    [(> (rest a-lon) (rest another-lon))true]
    [else false]))))) 

这没用。

【问题讨论】:

    标签: list scheme racket


    【解决方案1】:

    不幸的是,你的语法和逻辑都错了。我相信你的意图是写这样的东西:

    (define (each-bigger? lst1 lst2)
      (cond
        ((and (null? lst1)  (null? lst2)) #t) ; both lists are empty => true
        ((or  (null? lst1)  (null? lst2)) #f) ; only one is empty => not the same length => false
        ((>=  (car lst1)    (car lst2))   #f) ; first element of lst1 >= first element of lst2 => false
        (else (each-bigger? (cdr lst1) (cdr lst2))))) ; recur on the rest of the list
    

    可以简写为

    (define (each-bigger? lst1 lst2)
      (or (and (null? lst1) (null? lst2))               ; EITHER both lists are empty
          (and (not (or (null? lst1) (null? lst2)))     ; OR  1) none of them is empty
               (< (car lst1) (car lst2))                ;     2) AND first element of lst1 < first element of lst2
               (each-bigger? (cdr lst1) (cdr lst2)))))  ;     3) AND each-bigger? is true for the rest of both lists
    

    希望这会有所帮助!

    【讨论】:

      【解决方案2】:

      显然,您想从头开始实施解决方案,@uselpa 的建议很准确。但在非学术环境中,您应该使用现有程序来解决此类问题,特别是 andmap 是您最好的朋友:

      (define (each-bigger? lst1 lst2)
        (and (= (length lst1) (length lst2))
             (andmap < lst1 lst2)))
      

      诀窍在于andmap 对两个列表的元素应用谓词,将lst1 的第一个元素和lst2 的第一个元素作为参数传递,然后lst1 的第二个元素和第二个元素传递lst2,等等(顺便说一句,andmap 接受 一个或多个列表作为参数,只要谓词接收相同数量的参数)。

      如果谓词的所有应用程序都返回#t,则返回#t,如果单个谓词返回#f,则评估停止并返回#f。在上面的示例中,谓词只是&lt;,在两个列表之间成对应用。它按预期工作:

      (each-bigger? '(1 2 3) '(2 4 5))
      => #t
      (each-bigger? '(1 2 3) '(0 4 1))
      => #f
      (each-bigger? '(1 2 3) '(2 4 5 6))
      => #f
      

      【讨论】:

      • 很遗憾andmap 无法处理列表大小不同的情况。
      • @uselpa 对这个问题没问题,如所述:“编写一个接受两个列表的函数(必须等长) ...”
      • 它还说“会像 (1 2 3) 和 (1 2 3 4) 一样返回 false,因为它们的大小不同”。
      • @uselpa 嗯,我错过了那部分。对,我正在更新我的答案。感谢您指出!
      • 反对者:想发表评论吗?有什么改进我的答案的建议,或者它目前的状态有什么问题?
      猜你喜欢
      • 2013-08-06
      • 2019-05-05
      • 2021-02-25
      • 2017-12-24
      • 1970-01-01
      • 1970-01-01
      • 2023-01-13
      • 2019-03-08
      • 2019-12-07
      相关资源
      最近更新 更多