删除 Rebol 系列中最后一个元素的最简洁的方法是什么?
到目前为止我发现的选项是
s: "abc"
head remove back tail s
和
s: "abc"
take/last s
定义“最佳”。最高性能?最清晰?您希望表达式最后返回什么,或者您不在乎?您提供的两个返回不同的结果......一个是删除后系列的头部,另一个是删除的项目。
如果要删除后的系列头部,则需要take/last s
后跟s
以获取该表达式。比较:
>> delta-time [
loop 10000 [
s: copy "abc"
take/last s
s
]
]
== 0:00:00.012412
>> delta-time [
loop 10000 [
s: copy "abc"
head remove back tail s
]
]
== 0:00:00.019222
如果您希望表达式评估为已删除的项目,则需要与take/last s
诸如...之类的复杂内容进行比较,also (last s) (remove back tail s)
因为还将运行第一个表达式,然后运行第二个...返回第一个表达式的结果:
>> delta-time [
loop 10000 [
s: copy "abc"
take/last s
]
]
== 0:00:00.010838
>> delta-time [
loop 10000 [
s: copy "abc"
also last s remove back tail s
]
]
== 0:00:00.024859
等等
If you don't care about the result, I'm going with take/last
. If you do care about the result and want the head of the series, I'm going with take/last s
followed by s
. To me that reads better than head remove back tail s
, although it's an aesthetic choice. It's still faster, at least on my netbook.
If you want the tail of the series at the end of the expression, remove back tail s
is surprisingly similar in performance to take/last s
followed by tail s
. I'd say the latter is more explicit, and probably preferable, in case the reader forgets the return convention of REMOVE.
And also last s remove back tail s
looks terrible, but is a reminder about also
, which is pretty useful and easy to forget it's there. FWIW, it performs about the same as using an intermediate variable.
Here I wrote a REMOVE-LAST function,
remove-last: func [
"Removes value(s) from tail of a series."
series [series! port! bitset! none!]
/part range [number!] "Removes to a given length."
] [
either part [
clear skip tail series negate range
] [
remove back tail series
]
]
Example use:
b: [a b c d e f g]
remove-last b ;== [], 'g removed, tail of the series return.
head remove-last/part b 2 ;== [a b c d], 'e and 'f removed
It returns the tail of the series to be able to use in following situation;
b: [a b c d e f g]
head insert remove-last b 'x ;== [a b c d e f x]