我试图用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样式for循环的内置函数,或者我需要自己实现这个函数?
类似C语言中的等效结构看起来如下所示,但我不确定是否有可能在REBOL中实现相同的模式:
for(i = 0; i < 10; i++){
print(i);
}发布于 2014-05-17 15:43:39
由于使用了rebol3标记,我将假设这个问题与Rebol 3有关。
为Rebol 3提议"CFOR“
对于Rebol 3,有一个提议(得到了相当多的支持),它非常类似于C风格的for,因此目前也以cfor的名字命名:关于所有血淋淋的细节,请参见CureCode问题#884。
这包括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中所有控制结构的用户级实现,有一点是很重要的:在[throw]中还没有类似于Rebol 2的R3属性(参见CureCode问题#539),因此这种用户编写的(“夹层”)控制或循环函数在一般情况下都会出现问题。
特别是,此CFOR将错误地捕获return和exit。为了举例说明,请考虑以下功能:
foo: function [] [
print "before"
cfor [i: 1] [i < 10] [++ i] [
print i
if i > 2 [return true]
]
print "after"
return false
]您会(正确地)期望return实际上从foo返回。然而,如果您尝试以上所述,您会发现这种期望令人失望:
>> foo
before
1
2
3
after
== false这个注释当然适用于在这个线程中作为答案给出的所有用户级别的实现,直到bug #539被修复为止。
发布于 2014-05-17 11:32:32
有一个由Ladislav Mecir优化的Cfor
cfor: func [
{General loop}
[throw]
init [block!]
test [block!]
inc [block!]
body [block!]
] [
use set-words init reduce [
:do init
:while test head insert tail copy body inc
]
]发布于 2014-05-17 18:49:47
大多数人在这个特殊情况下使用的另一个控制结构是repeat。
repeat i 10 [print i]其结果是:
>> repeat i 10 [print i]
1
2
3
4
5
6
7
8
9
10我通常不经常使用loop,但是可以在类似的程度上使用它:
>> i: 1
>> loop 10 [print ++ i]
1
2
3
4
5
6
7
8
9
10这些是一些有用的控制结构。不确定你是否在寻找cfor,但你从其他人那里得到了这个答案。
https://stackoverflow.com/questions/23706547
复制相似问题