We have this code
(define (checksum-2 ls)
(let ([x (reverse ls)])
(cond
[(null? ls) 0]
[else (+ (* (length ls) (car x)) (checksum-2 (cdr x)))])))
It reverses this list
'(4 6 7 5 6)
It’s suppose to return 87 but it returns 80. Can anyone help us debug this?
As written, this function will return
This is because at each stage, it takes the first element of the reversed list (i.e. the last element of the list) and multiplies it by the list length, and adds it to the result of calling
checksum-2on the reversed list. The list is then reverse again, so the next element to be added is the one that was originally at the front of the list (which is4in this case).What you want to do is reverse the list once, and then work with the reversed list from then on. To do this you can use a helper function:
Now you only have to reverse the list once, which is a big win in efficiency. To clean up the code you can factor the definition of
chksum-helperinside the definition ofchksum, getting something like this:I renamed the argument to
chksum-helperfromlstoxto prevent confusion, but you don’t actually have to do this – it would work just as well if you left it asls. This is about as compact as you’re going to get it.