加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

REBOL中的C风格循环

发布时间:2020-12-16 10:26:11 所属栏目:百科 来源:网络整理
导读:我试图在REBOL中编写一个C风格的for循环: for [i: 0] [i 10] [i: i + 1] [ print i] 但是,此语法似乎不正确: *** ERROR** Script error: for does not allow block! for its 'word argument** Where: try do either either either -apply-** Near: try loa
我试图在REBOL中编写一个C风格的for循环:

for [i: 0] [i < 10] [i: i + 1] [
    print i
]

但是,此语法似乎不正确:

*** ERROR
** Script error: for does not allow block! for its 'word argument
** Where: try do either either either -apply-
** Near: try load/all join %/users/try-REBOL/data/ system/script/args...

REBOL是否具有类似于C-style for循环的任何内置函数,或者我是否需要自己实现此函数?

类似C语言的等效结构看起来像这样,但我不确定是否可以在REBOL中实现相同的模式:

for(i = 0; i < 10; i++){
    print(i);
}

解决方法

由于 rebol3标签,我将假设这个问题与Rebol 3有关.

为Rebol 3提出的“CFOR”

对于Rebol 3,有一个提议(得到了相当多的支持),一个“通用循环”非常类似于C风格,因此目前也以cfor的名义出现:请参阅CureCode issue #884 for all血淋淋的细节.

这包括Ladislav原始实现的一个非常精炼的版本,当前(截至2014-05-17)版本我将在这里重现(没有广泛的内联评论讨论实现方面),以便于参考:

cfor: func [  ; Not this name
    "General loop based on an initial state,test,and per-loop change."
    init [block! object!] "Words & initial values as object spec (local)"
    test [block!] "Continue if condition is true"
    bump [block!] "Move to the next step in the loop"
    body [block!] "Block to evaluate each time"
    /local ret
] [
    if block? init [init: make object! init]

    test: bind/copy test init
    body: bind/copy body init
    bump: bind/copy bump init

    while test [set/any 'ret do body do bump get/any 'ret]
]

Rebol 3中用户级控制结构实现的一般问题

Rebol 3中控制结构的所有用户级实现的一个重要的一般注释:在R3中没有类似于Rebol 2的[throw]属性(参见CureCode issue #539),所以这样的用户编写(“夹层”,在Rebol术语中)通常,控制或循环功能有问题.

特别是,这个CFOR会错误地捕获返回和退出.为了说明,请考虑以下功能:

foo: function [] [
    print "before"
    cfor [i: 1] [i < 10] [++ i] [
        print i
        if i > 2 [return true]
    ]
    print "after"
    return false
]

你(正确地)期望回报实际上从foo返回.但是,如果您尝试以上操作,您会发现这种期望令人失望:

>> foo
before
1
2
3
after
== false

当然,这个注释适用于作为此线程中的答案给出的所有用户级实现,直到bug#539被修复.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读