[英]How to get a specific number of random elements from a collection in Smalltalk?
[英]How to copy at most n collection elements in Smalltalk?
是否有優雅的單行內容可以復制集合中的最多n個元素?
我發現編寫以下繁瑣的內容:
limit := collection size min: n.
copy := collection copyTo: limit
有沒有更好的辦法?
編輯 - 還有一個更難的問題:最多復制最后 n個元素
還有流消息:
'foobar' readStream next: 3.
'foobar' readStream next: 10.
在Squeak / Pharo中使用next:
,當沒有可用的元素數時,它會自動截斷。
在其他方言如VW&Dolphin中使用更明確的nextAvailable:
以避免錯誤。
不確定是否已經存在完全符合他的方法,但您可以添加一個:
SequenceableCollection>>#copyAtMost: n
^ self first: (self size min: n)
然后你可以:
collection := 1 to: 100.
collection copyAtMost: 101
沒有專門的消息,但為什么不:
aCollection first: (aCollection size min: n)
和
aCollection last: (aCollection size min: n)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.