问题
This is a follow-up to this question.
I have lists or "records" that are appended together into an empty list, that are each in the format (Matthew (AL 21 32))
. I am now trying to write a function that would use fetchRecord
in order to find the desired record and then multiply the two numbers inside the record. However, my current code works only if I am getting the name on the first record but it returns an empty list for any record after that. Here is my code:
(define (Mult_Num name)
(cond
[(empty? db) #f]
[else (* (car(cdr(car(cdr (fetchRecord name)))))
(car(cdr(cdr(car(cdr (fetchRecord name)))))))]))
How would I fix this? Also if a certain record has two sets of data like so: (John (AL 25 40) (CA 40 67))
then how would you get both 25*40 and 40*67 etc., and even if it has more than two sets of data? I understand that it would be recursion but am not quite sure how you would set it up.
This is my fetchRecord function:
(define (fetchRecord name)
(cond
[(empty? db) #f]
[(equal? (car (car db)) name) (car db)]
[else( car (car db)) name (cdr db)]))
This Also may be relevant:
(define db '())
Also I have this but if I have more than two names in here it screws itself up:
(define(showRec name) ;displays everything following a name.
(cond
[(empty? db) #f]
[(equal? (car (car db)) name) (cdr (fetchRecord name))]
[else (cdr (car(fetchRecord name)))])
)
回答1:
The main problem is that you rely on fetchRecord
which not only does not work, but isn't valid Scheme: the else
clause should have only 1 argument, not 3.
And you shouldn't be surprised that a function that would use recursion to handle the rest
of a list doesn't handle the rest
of a list when it doesn't use recursion.
来源:https://stackoverflow.com/questions/39693560/how-to-recursively-go-through-list-of-lists-and-combine-the-lists-in-different-w