Hi I am trying to write a program where given a list of lists check to see if they are equal in size and return #t if they are.
So for example if i were to write (list-counter? ‘((1 2 3) (4 5 6) (7 8 9))) the program would return #t, and (list-counter? ‘((1 2 3) (4 5 6) (7 8))) would return #f.
SO far this is what I have done:
(define list-counter?
(lambda (x)
(if (list? x)
(if (list?(car x))
(let (l (length (car x))))
(if (equal? l (length(car x))))
(list-counter?(cdr x))
) ) ) ) )
I think where I am going wrong is after I set the length of l to the length of the first list. Any help would be appreciated.
There are several ways to solve this problem. For instance, by hand and going step-by-step:
Let me explain the above procedures. I’m dividing the problem in two steps, first create a new list with the lengths of each sublist – that’s what
all-lengthsdoes. Then, compare the first element in a list with the rest of the elements, and see if they’re all equal – that’s whatall-equal?does. Finally,list-counter?wraps it all together, calling both of the previous procedures with the right parameters.Or even simpler (and shorter), by using list procedures (higher-order procedures):
For understanding the second solution, observe that
all-lengthsandall-equal?represent special cases of more general procedures. When we need to create a new list with the result of applying a procedure to each of the elements of another list, we usemap. And when we need to apply a procedure (=in this case) to all of the elements of a list at the same time, we useapply. And that’s exactly what the second version oflist-counter?is doing.