1

I'm defining a function ("my-function" below) making use of three lists. It checks if those three lists satisfy a certain condition and then do something more. This condition is to have length 2 (I suspect this is not important but I prefer to mention it). Therefore, it has the form:

(define my-function (lambda (list1 list2 list3)
    (cond                                                                            
     [(and (= (length list1) 2) (= (length list2) 2) (= (length list3) 2))...

My question is: how could I generalize "my-function" to a number of lists?

More generally: is there a way to index the lists into the input of the function and then call them one-by-one to check the condition?

Riccardo
  • 1,083
  • 2
  • 15
  • 25
gibarian
  • 133
  • 6

1 Answers1

2

You can use andmap to check whether a condition holds for all elements in a list:

(define lsts (list list1 list2 list3 list4))
(andmap (lambda (lst) (= (length lst) 2))
        lsts)

The trick is to create a list with the elements that you want to check, in this case, they're lists themselves. And to generalise this even more, you could pass the lambda that does the checking as a parameter, and you could pass the sublists as variable arguments:

(define (my-function check . lsts)
  (andmap check lsts))

(my-function (lambda (lst) (= (length lst) 2))
             list1 list2 list3 list4)
Óscar López
  • 232,561
  • 37
  • 312
  • 386
  • @PetSerAl you're right, thank you for catching that! It's fixed now. – Óscar López Nov 05 '18 at 13:28
  • 1
    Thank you. It works. I had never seen "check . lsts" as an input. What is doing that dot in the middle? – gibarian Nov 05 '18 at 14:44
  • 1
    `check` and `lsts` are just parameter names. `check` is a function and `lsts` is a list of lists, the dot in the middle is for declaring a variable number of arguments, see this [post](https://stackoverflow.com/a/12658435/201359). – Óscar López Nov 05 '18 at 14:47
  • I'll do it. Gracias de nuevo! – gibarian Nov 05 '18 at 14:50
  • Now my question is: how do I work with every pair? Is there a way to call every list into the list of lists? for example: (define (my-function lst) (make-list (second lst) (first lst)) lsts) would work? – gibarian Nov 08 '18 at 12:51
  • That’s worth a new question. Check the ‘map’ procedure, I think it’s what you need. – Óscar López Nov 08 '18 at 12:56