如何将红色/Rebol 字符串转换为系列

use*_*316 5 string rebol block series red

我想知道是否有办法将字符串转换为系列。我正在尝试使用 parse 提取数据,我想将一些捕获的数据分解成更小的片段,以便我可以执行 IF、CASE 或 SWITCH 语句。

下面是一些代码。

; A line of text with simple markup
current-line: {[chapter 1] The Wanderer}

; Parse the current line of input
parse current-line [
  "["
  copy tag to "]"
  skip
  copy rest-of-line to end
]

; Just some output to see if i captured data properly
print ["Extracted: " tag]
print ["Rest of line: " rest-of-line]

; The statements below both execute
; but the second one definitely shouldn't execute.
if [find tag  "chapter"] [print "The tag is chapter."]
if [find tag  "list"]    [print "The tag is list."]
Run Code Online (Sandbox Code Playgroud)

据我了解,“查找”适用于一个系列,这可能是那些 if 语句没有给出我期望的结果的原因。然而变量“tag”只是一个字符串。

有没有办法将字符串转换为系列?或者是否有任何函数可以处理字符串以查找子字符串?

Hos*_*ork 2

下面的语句都执行,但第二个语句绝对不应该执行。

if [find tag  "chapter"] [print "The tag is chapter."]
if [find tag  "list"]    [print "The tag is list."]
Run Code Online (Sandbox Code Playgroud)

这是一个非常常见的新用户问题,也是可以理解的。

关于 BLOCK 需要记住的关键一点!一个块“只是数据”,除非您(或您调用的函数)通过​​使用 DO 执行它来“使该块栩栩如生”。查看IF的帮助:

>> help if

USAGE:
    if cond then-blk

DESCRIPTION:
    If condition is true, evaluate block; else return NONE.
    if is of type: native!

ARGUMENTS:
    cond [any-type!]
    then-blk [block!]
Run Code Online (Sandbox Code Playgroud)

您必须将 THEN-BLOCK 作为值传递,因为它是否会“生效”并由 IF 运行取决于条件是否为真。IF 必须决定是否执行该块。

但 IF 的第一个参数是条件。无论条件最终为真还是假,每次命中 IF 语句时都必须运行它。因此,该条件不存在块的“样板”。缺乏样板意味着如果您将块作为数据传递给它,那么问题就归结为“数据块被视为值,是真还是假?” 嗯……确实如此:

>> true? [some arbitrary block]
== true
Run Code Online (Sandbox Code Playgroud)

事实上,除了 NONE 之外,所有值都被视为“有条件为真”!价值或逻辑!错误的。即使为零也是正确的:

>> if 0 [print "Almost absolutely every value is true!"]

Almost absolutely every value is true! 
Run Code Online (Sandbox Code Playgroud)

因此,您不想将您的条件放在方括号中。要么保留它,要么您可以使用括号块“组”。括号确实会计算,但会隔离计算的部分,这可以帮助您隔离子表达式以实现优先级或参数检查等目的。所以:

if find tag "chapter" [print "The tag is chapter."]
if (find tag "list") [print "The tag is list."]
Run Code Online (Sandbox Code Playgroud)

希望这是有道理的,但是您始终必须考虑评估模型以了解使用或不使用块的动机。例如,WHILE 循环与 IF 不同,因为它需要多次运行条件。

>> x: 0
>> while x < 2 [ 
    print x 
    x: x + 1 
]

*** Script error: while does not allow logic for its cond argument
Run Code Online (Sandbox Code Playgroud)

当定义 WHILE 时,它必须为条件占用一个块。因为否则 WHILE 函数会将其第一个参数计算为 TRUE,然后x < 2每次循环时都不会计算表达式。所以:

>> x: 0
>> while [x < 2] [ 
    print x 
    x: x + 1 
]

0
1
Run Code Online (Sandbox Code Playgroud)

你很可能会犯错误;如果将 WHILE 转换为 IF,则特别容易。然而,尽管 IF可以被设计为在其条件周围强制执行样板代码块(即使对于一次性评估条件的东西来说不是必需的),但在不必要的地方反击样板代码是系统的目标之一。

好消息是,它背后有一个逻辑和规则......一旦掌握了它,您就可以用来制作自己的循环结构等等。“疯狂,但有一个方法。” :-)

我想知道是否有办法将字符串转换为系列。我正在尝试使用解析来提取数据,并且我想将一些捕获的数据分解为更小的片段,以便我可以执行 if、case 或 switch 语句。

用当今的术语来说(在其他一些情况下可能有点令人困惑),字符串!已经是该系列的成员!排版。也就是说,您可以执行诸如使用 FIRST 或 SECOND 从中选取元素,或者使用 NEXT 遍历它等操作。这就是 SERIES。