0". 5. s -6ren">
gpt4 book ai didi

smalltalk - 某些 WriteStream 消息背后的逻辑是什么?

转载 作者:行者123 更新时间:2023-12-02 22:43:52 26 4
gpt4 key购买 nike

考虑以下消息序列:

1. s := '' writeStream.
2. s nextPutAll: '123'.
3. s skip: -3.
4. s position "=> 0".
5. s size "=> 3".
6. s isEmpty "=> false".
7. s contents isEmpty "=> true (!)"

6 和 7 不是矛盾的,或者至少是令人困惑的吗?这种行为背后的逻辑是什么? (Dolphin 也有类似的功能。)

更新

正如 @MartinW 观察到的(请参阅下面的评论)ReadStreamReadWriteStream 的行为不同(我们可以说,正如预期的那样。)

从实际角度来看,我更担心的兼容性是与 FileStream 的兼容性,其中 contents 消息不限于当前位置。 这样这种差异使原本很好的“法则”失效,根据该法则,任何使用内存流(字符串或字节数组)的代码也可以使用文件流,反之亦然。这种等价对于测试和教学来说非常有用。通过将方法 #truncate 添加到 WriteStream 中,可以轻松恢复明显的功能损失,该方法会显式地将 size 缩短为当前的 立场 [参见下面与德里克·威廉姆斯的讨论]

最佳答案

在许多 Smalltalks(如 VAST)中,方法注释很好地解释了这一点:

WriteStream>>contents
"Answer a Collection which is a copy collection that the receiver is
streaming over, truncated to the current position reference."

PositionableStream>>isEmpty
"Answer a Boolean which is true if the receiver can access any
objects and false otherwise."

注意“截断为当前位置引用。”

在您的示例中,contents 是一个空字符串,因为您使用 skip: -3 将位置设置回 0。

这种行为不仅是正确的,而且非常有用。例如,考虑一个从集合构建逗号分隔列表的方法:

commaSeparatedListFor: aCollection 

ws := '' writeStream.
aCollection do: [ :ea |
ws print: ea; nextPutAll: ', ' ].
ws isEmpty
ifFalse: [ ws position: ws position - 2 ].
^ws contents

在这种情况下,该方法可能已写入最后的尾随“,”,但我们希望 contents 将其排除。

关于smalltalk - 某些 WriteStream 消息背后的逻辑是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29055751/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com