Ternary operator in a single line function

In Julia, I may need 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 fairly simple function, and the verbosity of the five-line if else is probably excessive. So I am trying to turn it into a single line function. The best I can think of is the following:

 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 simpler ways to define this function?

+6
source share
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 
+10
source

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 to be executed, which imho makes the C-like ternary operator redundant. As in the case, all its functions are covered by a more readable alternative.

Looking at your previous attempts, I think it's worth mentioning that, unlike Python, you rarely need to explicitly use return (). Often you can simply return all returned if-elseif-else blocks, as with most lisp dialects. An explicit return is like goto or break, which you use to interrupt the control flow in exceptional cases.

+2
source

Source: https://habr.com/ru/post/988127/


All Articles