VansFannel
VansFannel

Reputation: 45921

Compare all the elements of a list of lists without using andmap

I have these two lists:

(define casos ’((a 3 15 r +)(l 41 9 -)))
(define extension ’((b 4 5 r -)(c 4 90 d -)))

I want to get the number of lists of these two list that have different its last element (+ or -).

To do it, I have used andmap:

(define iguales 0)

(andmap
    (lambda (x y)
        (cond 
          ((eq? (last x) (last y)) 
             (set! iguales (add1 iguales)))) iguales)
    casos extension) 

If I run this code with the previous lists, igualeswill be 1.

I don't think andmap is the right way to do it.

Is there a better way to do that without using andmap?

Upvotes: 0

Views: 79

Answers (1)

Óscar López
Óscar López

Reputation: 235994

If you need to count how many elements meet a condition, then use count, it's pretty straightforward, and you can pass more than one list as parameter (as is your case):

(define casos '((a 3 15 r +)(l 41 9 -)))
(define extension '((b 4 5 r -)(c 4 90 d -)))

(count (lambda (caso ext) (eq? (last caso) (last ext)))
       casos
       extension)

=> 1

For this case in particular, andmap is not the right tool. In general: avoid using set!, most of the time you can do what you want in a functional-programming style. Please take some time to study the list procedures available in the standard library.

Upvotes: 3

Related Questions