rebol - 如何在 Rebol 2 中对列表进行分区

标签 rebol rebol2

如何在 Rebol 2 中对列表进行分区?我不关心分区的最终顺序。

例如我想象会有一个类似这样的函数:

lst: [1 5 6 5 5 2 1 3]

probe partition lst  ; Assuming identity function by default
[[1 1] [5 5 5] [6] [2] [3]]

probe partition/by lst even?
[[6 2] [1 5 5 5 1 3]]

如果没有这样的内置函数,那么在 Rebol 中构造它的惯用方法是什么?

最佳答案

这是一个惯用的尝试:

partition-unique: func [
    s [block!]
    /local got more
][
    collect [
        parse sort copy s [
            any [
                copy got [
                    set more skip
                    any more
                ] (keep/only got)
            ]
        ]
    ]
]

partition-by: func [
    s [block!]
    f [any-function!]
    /local result
][
    result: reduce [make block! 0 make block! 0]
    forall s [append pick result f s/1 s/1]
    result
]

使用示例:

>> lst: [1 5 6 5 5 2 1 3]
== [1 5 6 5 5 2 1 3]

>> partition-unique lst
== [[1 1] [2] [3] [5 5 5] [6]]

>> partition-by lst :even?
== [[6 2] [1 5 5 5 1 3]]

很容易将这些组合成一个函数。以下内容可以向您提供基本概念:

partition: func [
    s [block!]
    /by f [any-function!]
][
    either by [partition-by s :f] [partition-unique s]
]

关于rebol - 如何在 Rebol 2 中对列表进行分区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47279566/

相关文章:

rebol - 使用代码块中隐含的对象字段

Rebol 2 在升级到 Ubuntu 15.10 后停止工作

object - 为什么在Rebol2中动态添加代码到对象不生效?

rebol - 如何在 Freya 上运行 Rebol

重建 2 : Using a parse rule to check input without executing code

rebol - 如何在 Rebol 2 中将变量的内容写入文本文件?

user-interface - 在 Rebol 中刷新图像

url-routing - Rebol 3 方案中的用户/密码

rebol - 从 Rebol 中的系列中删除重复的对象

error-handling - 当我使用错误?并尝试,错误需要一个值