2014-04-26 14 views
8

ho notato che REBOL non ha una costruito nel if...elsif...else sintassi, come questo:if ... else if ... else in REBOL

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!" 
] 

ho trovato una soluzione, ma è estremamente verbose:

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!" 
      ] 
     ] 
] 

c'è un modo più conciso per implementare una catena if...else if...else in REBOL?

risposta

8

Il costrutto che si sta cercando sarebbe CASE. Occorrono una serie di condizioni e blocchi di codice per valutare, valutando i blocchi solo se la condizione è vera e si ferma dopo che è stata soddisfatta la prima condizione vera.

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!" 
    ] 
] 

Come si vede, ottenendo un valore predefinito è semplice come virare su una condizione TRUE.

Inoltre: se lo si desidera, è possibile avere tutti i casi in esecuzione e non in cortocircuito con CASE/ALL. Ciò impedisce al caso di fermarsi alla prima vera condizione; li eseguirà tutti in sequenza, valutando eventuali blocchi per qualsiasi condizione vera.

2

È possibile utilizzare il costrutto case per questo o il costrutto dell'interruttore.

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

Il costrutto caso viene utilizzato se si sta testando per condizioni diverse. Se stai guardando un particolare valore, è possibile utilizzare commutare

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

E una ulteriore opzione è quella di utilizzare tutte

all [ 
    expression1 
    expression2 
    expression3 
] 

e finché ogni espressione restituisce un valore vero, continueranno da valutare

così,

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

e abbiamo anche qualsiasi

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