映射!如果列表为空,则无法将元素追加到列表中?

发布于 2024-12-03 08:53:06 字数 620 浏览 0 评论 0原文

(require racket/mpair)

(define (bld-mlst . args)
  (list->mlist args))

(define mlst-my (bld-mlst))
mlst-my

(mappend! mlst-my (list->mlist (list 100)))
mlst-my

(define mlst-my2 (bld-mlst 2))

(mappend! mlst-my2 (list->mlist (list 100)))
mlst-my2

它会打印出:

(mcons 100 '())
'()
(mcons 2 (mcons 100 '()))
(mcons 2 (mcons 100 '()))

第一行和第三行只是mappend的返回值!注意第二行和第四行!我们可以看到第二行是'(),意思是mappend!不会改变 mlst-my!当 mlst-my2 不为空时,mapend! 工作正常。 问题: 那么如何制作mappend!当 mlist 为空时仍然会对 mlist 产生副作用吗?

(require racket/mpair)

(define (bld-mlst . args)
  (list->mlist args))

(define mlst-my (bld-mlst))
mlst-my

(mappend! mlst-my (list->mlist (list 100)))
mlst-my

(define mlst-my2 (bld-mlst 2))

(mappend! mlst-my2 (list->mlist (list 100)))
mlst-my2

it will print out:

(mcons 100 '())
'()
(mcons 2 (mcons 100 '()))
(mcons 2 (mcons 100 '()))

The first and third line is just the return value of the mappend! Note the second line and fourth line! We can see that the second line is '(), which means that mappend! does not change the mlst-my! While when the mlst-my2 is not empty, the mappend! works fine.
Question:
Then How to make the mappend! to still side effect the mlist when the mlist is empty?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

很快妥协 2024-12-10 08:53:06

你不能!空列表是一个单例、不可变的对象。它没有可以更改的插槽(car 或 cdr)。但您可以这样做:

(set! mlst-my (mappend! mlst-my (list->mlist (list 100))))

也就是说,您set!您的变量为mappend!的返回值。


要了解这一切,请了解单链表的工作原理。它由cons 单元(或点对)组成,每个单元都有两个插槽(传统上称为carcdr) 。 car 槽指向值,cdr 指向下一个 cons/pair。

因此,像 (1 2 3) 这样的列表具有三个 cons:

#0=(1 . #1#)
#1=(2 . #2#)
#2=(3 . ())

append! 的工作方式是找到最后一个 cons(其 cdr 指向 ()),并将其 cdr 更改为指向您要附加的列表。

但是,如果您的列表为空,则它没有任何缺点,因此无需更改。空列表始终是不可变的。

You can't! The empty list is a singleton, immutable object. It has no slots (car or cdr) that you can change. But you can do this:

(set! mlst-my (mappend! mlst-my (list->mlist (list 100))))

That is, you set! your variable to mappend!'s return value.


To understand all that, understand how singly linked lists work. It comprises cons cells (or dotted pairs), which each have two slots (traditionally named car and cdr). The car slot points to the value, and the cdr points to the next cons/pair.

So, a list like (1 2 3) has three conses:

#0=(1 . #1#)
#1=(2 . #2#)
#2=(3 . ())

The way append! works is to find the last cons (the one whose cdr is pointing to ()), and change its cdr to point to the list you're appending.

If your list is empty, though, it has no conses, and therefore it has nothing to change. Empty lists are always immutable.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文