Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The ternary operator in a one-line function

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?

like image 551
Colin T Bowers Avatar asked May 29 '15 03:05

Colin T Bowers


People also ask

What is the function of ternary operator?

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.

Which operator is used as ternary operator?

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 .

What is the function of ternary operator in C?

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");

What is ternary operator with example?

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.


2 Answers

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
like image 59
spencerlyon2 Avatar answered Sep 19 '22 23:09

spencerlyon2


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.

like image 22
saolof Avatar answered Sep 21 '22 23:09

saolof