方案:添加到记录列表
我正在为学校做一项计划作业,有一个问题涉及我们定义记录“类型”(作为列表实现)(代表音乐记录)。
我遇到的问题是,要求我创建一个过程来创建这些记录的列表,然后创建一个函数来将记录添加到该列表中。这很简单,但我觉得我可能做错了什么。
我知道如何将元素附加到列表(即本例中的记录架),但我不确定如何在调用此 add
函数时正确维护此列表。这就是我所得到的:
(define (add-record record lst)
(append lst (list record)))
它按我的预期工作,但我的问题是当我调用此过程时。
(define record-self '())
这是我的第一次尝试,但当然每次我使用 add-record
过程添加记录时,传入刚刚定义的 record-shelf
列表,嗯,我的添加函数返回一个全新的列表(即带有附加记录的副本)。这是有道理的,但我不确定这是否是我想要的。
因此,如果我想像这样向列表中添加一堆记录:
(add-record highway61 record-shelf)
(add-record sgtPepper record-shelf)
当然,它不会产生我想要的结果,因为 record-shelf
没有更新。我认为在课程的这一点上我们不应该使用 set!
或作业。
我是否应该每次都获取返回列表的副本(来自 add-record
),然后在下一次调用中使用该返回列表?
I'm working on a Scheme assignment for school and there's a question involving us defining a record "type" (implemented as a list) (which represents a music record).
The question I'm having trouble with is I'm asked to create a procedure which creates a list of these records, and then a function to add a record to this list. This is pretty simple, but I feel like I might be doing something wrong.
I know how to append an element to a list (i.e. the record shelf in this example), but I'm not sure how to properly maintain this list across invocations of this add
function. Here's what I've got:
(define (add-record record lst)
(append lst (list record)))
Which works as I'd expect, but my problem is when I invoke this procedure.
(define record-self '())
Was my first attempt, but of course every time I add a record with the add-record
procedure, passing in that just-defined record-shelf
list, well, my add function returns a brand new list (i.e. a copy, with the appended record). This makes sense, but I'm not sure if that's what I want.
So if I wanted to add a bunch of records to the list like so:
(add-record highway61 record-shelf)
(add-record sgtPepper record-shelf)
Of course it doesn't result in what I want, because record-shelf
doesn't get updated. And I don't think at this point in the course we're supposed to use set!
or assignments.
Should I just be grabbing a copy of the returned list (from add-record
) every time, and then use that returned list in the next invocation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您希望有状态行为。正如恩里克所说,你最后一个问题的答案是肯定的。
您是否有理由不能将新记录
cons
到列表的头部?这是在 Lisp 中向列表添加项目的惯用方法。或者在任何使用单链表的函数式语言中。在调用
add-record
后,如果不以某种形式使用set!
,就无法使record-shelf
包含新项目。You are wishing for stateful behavior. As Enrique says, the answer to your last question is Yes.
Is there a reason you can't just
cons
the new record onto the head of the list? That is the idiomatic way to add items to a list in Lisp. Or in any functional language that uses singly linked lists.There is no way to make
record-shelf
contain a new item after you invokeadd-record
without usingset!
in some form.