Question

I am trying to write a function that takes two lists (must be of equal length) and then goes through each list comparing individual items.

For example: (1 2 3) and (2 4 5) would return true because each element of list 2 is greater than the corresponding element in list 1. (1 2 3) and (0 4 1) would return false as would (1 2 3) and (1 2 3 4) since they are of different size. Using 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]))))) 

this didn't work.

No correct solution

OTHER TIPS

Unfortunately you've got both your syntax and your logic wrong. I believe your intention was to write something like this:

(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

which can be shortened to

(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

Hope this helps!

Clearly you want to implement a solution from scratch, and @uselpa's advice is spot-on. But in a non-academic context you should use existing procedures for solving this kind of problem, in particular andmap is your best friend here:

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

The trick is that andmap applies a predicate on elements of both lists, passing as parameters the first element of lst1 and the first element of lst2, then the second element of lst1 and the second element of lst2, and so on (BTW, andmap accepts one or more lists as parameters, as long as the predicate receives the same number of parameters).

If all the applications of the predicate return #t then #t is returned, if a single predicate returns #f then evaluation stops and #f is returned. In the above example, the predicate is just <, applied pair-wise between the two lists. It works as expected:

(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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top