I am trying to build a procedure to compare two lists (that are elements of a larger list) and return how similar they are. The procedure will do this by summing the difference between the elements in the same index in both lists. This is done recursively by comparing the car
of both lists, calling on itself again with the running result being the comparison and the new lists being the cdr
of both lists, and finally returning the result when both lists are empty. However, when I test this, the following error is returned even though I have an if
statement to return the result when the lists are null:
Cannot read property 'car' of undefined [ ]
I'm fairly certain that my let
syntax is correct, as that was fixed in a prior question, and the only other time car
is used in the other procedure used doesn't have any errors when run by itself. What is happening and how can it be fixed?
Code:
(define (get-list name arr)
(if (eq? name (car (car arr)))
(cdr (car arr))
(get-list name (cdr arr))))
(define (similarity-arrays name1 name2 arrs result)
(let ((arr1 (get-list name1 arrs))
(arr2 (get-list name2 arrs)))
(if (= (length arr1)(length arr2))
(let ((x1 (car arr1))
(x2 (car arr2)))
(if (null? arr1))
result
(similarity-arrays
(cdr arr1)
(cdr arr2)
(+ result (- x1 x2)))))
#f))
(define dust
(list (list 'akko 11 3 7 5 4 1 9 8 10 6 2)
(list 'Jodast 10 7 4 6 5 1 11 9 8 3 2)
(similarity-arrays 'Jodast 'Akko dust 0)