0
votes
    (define mylist (list (list 'a (list 'b 'c)) (list 'b (list 'a 'd))
            (list 'c (list 'a 'd)) (list 'd (list 'c 'b 'a))))

    (define (total1 L)
            (+ (length (cdr (car L))) (total1 (cdr L))))

My aim is count lengths of sublists and sum this values.

length (('b 'c) + ('a 'd) + ('a 'd) + ('c 'b 'a))

So my function should return 9. But when I call this function, I get this error:

car: contract violation expected: pair? given: ()

What I should do?

1

1 Answers

0
votes

To solve the error, you should introduce a test to check if you are at the end of your list. Like this:

(define (total L)
    (if (null? L)
        0 ;has to be 0 because it will be +'ed in the recursion
        (+ (length (cdr (car L))) ;should be (car (cdr (car L))) or (cadar L)
           (total (cdr L)))))

This code still gives a wrong result though, because the (cdr (car L)) returns ((b c))for the first sublist and the length of this is 1, because is it a list with 1 element, the list (b c). What you want is the (car (cdr (car L)))