2014-02-23 73 views
1

我试图编写一个函数,它需要两个列表(必须具有相同的长度),然后遍历每个列表比较单个项目。在DrRacket中比较两个相同长度的列表中的单个元素

例如:因为列表2中的每个元素是大于在列表中的相应元件1 (1 2 3)(0 4 1)将返回false如将(1 2 3)(1 2 3 4),因为它们是不同的尺寸和(1 2 3)(2 4 5)返回true。使用博士球拍

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

这没有奏效。

回答

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 

希望这有助于!

1

很明显,您想从零开始实施解决方案,而@ 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。在上面的例子中,谓词只是<,在两个列表之间成对应用。它按预期工作:

(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 
+0

不幸的是,'andmap'不处理列表不具有相同大小的情况。 – uselpa

+0

@uselpa对于这个问题,这是正确的,正如所述:“写一个函数,需要两个列表_(必须是相等的长度)_ ...” –

+1

它也说“将返回错误将会(1 2 3)和(1 2 3 4),因为它们大小不同“。 – uselpa

相关问题