Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Julia: Can conditional statements evaluate code on the same line?

I am reading through the Julia manual right now and ran into my first potential disappointment.

I like being able to code conditional statements tersely. In R I might write:

if (x==y) print("Hello")

In Julia however I think I might need do

if x==y
  println("Hello")
end

Or perhaps x==y ? print("Hello") : print("") which is certainly silly.

Is there some formulation in Julia for allowing for single line conditional statements?

like image 813
Francis Smart Avatar asked Apr 09 '14 10:04

Francis Smart


1 Answers

You can write if x == y println("Hello") end or, as has become somewhat idiomatic, you can use the short-circuiting behavior of the && operator and write x == y && println("Hello"). In a very similar fashion it is fairly common to check some condition and throw an error if it isn't met by writing something like this: size(A) == size(B) || error("size mismatch").

like image 143
StefanKarpinski Avatar answered Sep 17 '22 15:09

StefanKarpinski