如何递归地列出列表,并以不同的方式组合列表 [英] How to recursively go through list of lists and combine the lists in different ways
问题描述
这是此问题的后续行动。
我将列表或记录附加在一个空列表中,格式为(Matthew(AL 21 32))
。我现在正在尝试编写一个使用 fetchRecord
的函数,以便找到所需的记录,然后将两个数字相乘。但是,我现在的代码只有在我在第一个记录上获得该名称时才能工作,但是之后返回一个空列表。这是我的代码:
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)))))))]))
我该如何解决?另外如果某个记录有两组数据,如下所示:(John(AL 25 40)(CA 40 67))
那么你将如何获得25 * 40和40 * 67等,即使它有两套以上的数据呢?我知道这将是递归的,但不太确定你将如何设置它。
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.
这是我的fetchRecord函数:
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)]))
这也可能是相关的: p>
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)))])
)
推荐答案
主要问题是您依靠 fetchRecord
,这不仅不起作用,无效方案: else
子句应该只有1个参数,而不是3。
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.
令人惊讶的是,使用递归来处理列表的休息
的函数不会处理 rest
一个列表,当它不使用递归。
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.
这篇关于如何递归地列出列表,并以不同的方式组合列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!