Conditional structures: Difference between revisions
Content added Content deleted
(+ МК-61/52) |
|||
Line 3,013: | Line 3,013: | ||
In general a dispatch table or class/object abstraction (using dynamic method over-rides) is considered preferable to chains of ''if ... elif ... elif ...'' in Python programming. |
In general a dispatch table or class/object abstraction (using dynamic method over-rides) is considered preferable to chains of ''if ... elif ... elif ...'' in Python programming. |
||
=={{header| |
=={{header|Racket}}== |
||
===if |
===if=== |
||
[http://docs.racket-lang.org/reference/if.html#%28form._%28%28quote._~23~25kernel%29._if%29%29 If-expressions] |
|||
<lang R>#Single line example |
|||
in Racket must have both branches |
|||
#x is assumed to be scalar |
|||
<lang Racket> |
|||
if(x < 3) message("x is less than 3") else if(x < 5) message("x is greater than or equal to 3 but less than 5") else message("x is greater than or equal to 5") |
|||
(if (< x 10) |
|||
#Block example |
|||
"small" |
|||
if(x < 3) |
|||
"big") |
|||
{ |
|||
</lang> |
|||
x <- 3 |
|||
warning("x has been increased to 3") |
|||
} else |
|||
{ |
|||
y <- x^2 |
|||
} |
|||
#It is important that the else keyword appears on the same line as the closing '}' of the if block.</lang> |
|||
===ifelse=== |
|||
<lang r>#ifelse is a vectorised version of the if/else flow controllers, similar to the C-style ternary operator. |
|||
x <- sample(1:10, 10) |
|||
ifelse(x > 5, x^2, 0)</lang> |
|||
===switch=== |
|||
See [http://cran.r-project.org/doc/manuals/R-lang.html#switch doc] for R switch statement. |
|||
<lang r># Character input |
|||
calories <- function(food) switch(food, apple=47, pizza=1500, stop("food not known")) |
|||
calories("apple") # 47 |
|||
calories("banana") # throws an error |
|||
# Numeric input |
|||
alphabet <- function(number) switch(number, "a", "ab", "abc") |
|||
alphabet(0) # null response |
|||
alphabet(1) # "a" |
|||
alphabet(2) # "ab" |
|||
alphabet(3) # "abc" |
|||
alphabet(4) # null response |
|||
# Note that no 'otherwise' option is allowed when the input is numeric.</lang> |
|||
=={{header|Retro}}== |
=={{header|Retro}}== |