映射!如果列表为空,则无法将元素追加到列表中?
(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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你不能!空列表是一个单例、不可变的对象。它没有可以更改的插槽(car 或 cdr)。但您可以这样做:
也就是说,您
set!
您的变量为mappend!
的返回值。要了解这一切,请了解单链表的工作原理。它由cons 单元(或点对)组成,每个单元都有两个插槽(传统上称为
car
和cdr
) 。car
槽指向值,cdr
指向下一个 cons/pair。因此,像
(1 2 3)
这样的列表具有三个 cons: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:
That is, you
set!
your variable tomappend!
'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
andcdr
). Thecar
slot points to the value, and thecdr
points to the next cons/pair.So, a list like
(1 2 3)
has three conses:The way
append!
works is to find the last cons (the one whosecdr
is pointing to()
), and change itscdr
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.