In Julia, I might want to write a function that returns 0
if the input is less than 1
, or returns 2
if the input is greater than or equal to 1
. This is a pretty simple function, and the verbosity of a five-line if else
construct is probably excessive. So I'm trying to turn it into a one-line function. The best I can come up with is as follows:
f(x::Number) = begin (x < 1) && return(0); return(2); end
or
f(x::Number) = begin x < 1 ? (y=0) : (y=2); return(y); end
Are there any simpler ways to define this function?
The conditional (ternary) operator is the only JavaScript operator that takes three operands: a condition followed by a question mark ( ? ), then an expression to execute if the condition is truthy followed by a colon ( : ), and finally the expression to execute if the condition is falsy.
Remarks. The conditional operator (? :) is a ternary operator (it takes three operands). The conditional operator works as follows: The first operand is implicitly converted to bool .
We use the ternary operator in C to run one code when the condition is true and another code when the condition is false. For example, (age >= 18) ? printf("Can Vote") : printf("Cannot Vote");
It helps to think of the ternary operator as a shorthand way or writing an if-else statement. Here's a simple decision-making example using if and else: int a = 10, b = 20, c; if (a < b) { c = a; } else { c = b; } printf("%d", c); This example takes more than 10 lines, but that isn't necessary.
julia> f(x::Number) = x < 1 ? 0 : 2
f (generic function with 1 method)
julia> f(0)
0
julia> f(1)
2
julia> f(0.99)
0
Alternative solution:
f(x::Number) = if (x < 1) 0 else 2 end
The if-elseif-else syntax in Julia will return the value of the expression that gets executed, which imho makes the C-like ternary operator rather superfluous. As in, all of its functionality is encompassed by a more readable alternative.
Looking at your previous attempts, I think it is worth mentioning that unlike in say Python, you rarely need to explicitly use return(). Often you can just return whatever your if-elseif-else blocks return, much like you would in most lisp dialects. Explicit return is like goto or break, something that you use to break control flow in exceptional cases.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With