【问题标题】:If...else if...else in REBOL如果...否则如果...在 REBOL 中
【发布时间】:2014-06-12 00:04:09
【问题描述】:

我注意到 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 链?

【问题讨论】:

    标签: switch-statement rebol rebol3


    【解决方案1】:

    您要寻找的构造是 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 短路。这可以防止案例在第一个真实条件下停止;它将按顺序运行它们,评估任何块的任何真实条件。

    【讨论】:

      【解决方案2】:

      还有一个选择是全部使用

      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 ]
      

      【讨论】:

        【解决方案3】:

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

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

        如果您要测试不同的条件,则使用 case 构造。如果您正在查看特定值,则可以使用 switch

        switch val [
           va1 [ .. ]
           val2 [ .. ]
           val3 val4 [ either or matching ]
        ]
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-05-31
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多