Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulate ternary operator in Elixir

How to do the similar conditional one-line check in Elixir?

if (x > 0) ? x : nil 

Is this the only equivalent in elixir world?

if true, do: 1, else: 2 
like image 860
Teo Choong Ping Avatar asked Jun 25 '16 13:06

Teo Choong Ping


1 Answers

To me, the if IS the equivalent of a ternary operator as it evaluates to a value which for various other languages it doesn't.

so x = if false, do: 1, else: 2

is basically x = false? 1 : 2

Not sure why Ruby adopted it ( if you are coming from Ruby ) as it has assignable if statements. in C the ternary is useful as the code bloats with the equivalent if statements. Of course C programmers desperate for terseness went nuts and did many nested upon nested ternaries :)

like image 180
Keith Nicholas Avatar answered Oct 16 '22 16:10

Keith Nicholas