如果......其他如果......在REBOL中

时间:2014-04-26 05:57:21

标签: switch-statement rebol rebol3

我注意到REBOL没有内置if...elsif...else语法,就像这样:

theVar: 60

{This won't work}
if theVar > 60 [
    print "Greater than 60!"
]
elsif theVar == 3 [
    print "It's 3!"
]
elsif theVar < 3 [
    print "It's less than 3!"
]
else [
    print "It's something else!"
]

我找到了一种解决方法,但它非常冗长:

theVar: 60

either theVar > 60 [
     print "Greater than 60!"
 ][
        either theVar == 3 [
            print "It's 3!"
        ][
            either theVar < 3 [
                print "It's less than 3!"
            ][
                print "It's something else!"
            ]
        ]
 ]

在REBOL中实现if...else if...else链是否有更简洁的方法?

3 个答案:

答案 0 :(得分:8)

您要寻找的构造将是CASE。它需要一系列条件和代码块来评估,仅在条件为真时评估块并在满足第一个真条件后停止。

theVar: 60

case [
    theVar > 60 [
        print "Greater than 60!"
    ]

    theVar == 3 [
        print "It's 3!"
    ]

    theVar < 3 [
        print "It's less than 3!"
    ]

    true [
        print "It's something else!"
    ]
]

如您所见,获取默认值就像处理TRUE条件一样简单。

另外:如果您愿意,您可以使用CASE / ALL运行所有情况而不是短路。这可以防止案件在第一个真实条件下停止;它将按顺序运行它们,为任何真实条件评估任何块。

答案 1 :(得分:7)

另一个选择是使用所有

all [
   expression1
   expression2
   expression3
]

只要每个表达式返回一个真值,它们就会继续被评估。

所以,

if all [ .. ][
 ... do this if all of the above evaluate to true.
 ... even if not all true, we got some work done :)
]

我们也有

if any [
       expression1
       expression2
       expression3
][  this evaluates if any of the expressions is true ]

答案 2 :(得分:2)

您可以使用case构造或switch构造。

case [
   condition1 [ .. ]
   condition2 [ ... ]
   true [ catches everything , and is optional ]
]

如果您正在测试不同的条件,则使用案例构造。如果您正在查看特定值,则可以使用开关

switch val [
   va1 [ .. ]
   val2 [ .. ]
   val3 val4 [ either or matching ]
]
相关问题