Extended control flow?

I wrote some code with this structure

function(x)
  x >=0 && plot!(something)
  x <=0 && plot!(something different)
end

because I tried to select with the value of x what would be plotted: one of them of both plots at once. The code worked as expected for values of x lesser or equal to zero, but for positive values the return of the function was not a plot if not just the statement false.

How to make that my program work fine also for positive values of x?


I have also a second question: there is some macro or package that extends the control flow of Julia for something like cases? That is: a list of independent blocks of code that depend on a unique variable, something similar to what I tried in my toy program above, but that indeed execute each block independently.

Every statement in Julia is also an expression, including an if block, so (asuming you don’t want both expressions to execute when x==0) you could write

function(x)
    if x >= 0
        plot!(something)
    else
        plot!(something different)
    end
end

The return value will be the value produced by plot! on whichever branch was executed. Alternatively you could explicitly return if you like that more imperative style better:

function(x)
    if x >=0
        return plot!(something)
    else
        return plot!(something different)
    end
end

There is no case statement built into the language, but if you regularly do this kind of thing you could try Match.jl or a similar package: http://kmsquire.github.io/Match.jl/latest/#Match-Values-1

1 Like

Im asking exactly for the case that the executions are non exclusive, that is, I want that both plots execute when x==0. In short: I want some control flow for non exclusive blocks of code, that is, that the blocks of code would execute independently depending of one variable (the variable that chooses what blocks are executed and what aren’t).

Anyway thank you for the answer, I will take a look at the package Match.jl.

Well I guess you could do the following to solve your return value problem

function(x)
    x >= 0 && (p = plot!(something))
    x <= 0 && (p = plot!(something different))
    return p
end

or equivalent thing using if statements, but there’s no special syntax for that.

4 Likes

It worked like a charm, thank you.