在一系列!删除最后一个元素的最佳方法是什么

时间:2013-08-14 12:12:46

标签: rebol rebol3

删除Rebol系列中最后一个元素的最简洁方法是什么?

到目前为止我找到的选项是

s: "abc"
head remove back tail s

s: "abc"
take/last s

2 个答案:

答案 0 :(得分:3)

定义“最佳”。最高性能?最清晰?你希望表达式最终返回的是什么,或者你不关心?您提供的两个结果会返回不同的结果...一个是删除后系列的头部,另一个是删除的项目。

如果您想要删除系列文章的头部,则需要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 salso (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

如果你不关心结果,我会选择take/last。如果您确实关心结果并想要系列的主管,我将使用take/last s,然后是s。对我来说,它比head remove back tail s更好,尽管它是一种美学选择。它仍然更快,至少在我的上网本上。

如果您希望系列的尾部位于表达式的末尾,remove back tail s的效果与take/last s后跟tail s的惊人相似。我会说后者更明确,也许更可取,以防读者忘记了REMOVE的返回惯例。

并且also last s remove back tail s看起来很糟糕,但却提醒我also,这非常有用,很容易忘记它。 FWIW,它的表现与使用中间变量大致相同。

答案 1 :(得分:2)

这里我写了一个REMOVE-LAST函数,

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
    ]
]

使用示例:

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

它返回可以在以下情况下使用的系列的尾部;

b: [a b c d e f g]
head insert remove-last b 'x  ;== [a b c d e f x]
相关问题