I find myself with some frequency having to test a condition and, if that condition returns some value, do something with that value. For example:
x = [ 1, 2, 3 ]
itest = findfirst(isequal(2),x) # get value
if itest != nothing # test condition
deleteat!(x,itest) # use value
end
This can be done without defining test
outside the conditional, but calling findfirst
twice:
if findfirst(isequal(2),x) != nothing # test condition
i = findfirst(isequal(2),x) # get value again
deleteat!(x,i) # use value
end
Is there a way to use a more clean syntax as in the second case, but without repeating the findfirst
command?
In particular, this becomes useful if I want to add other associated conditionals:
x = [ 1, 2, 3 ]
if findfirst(isequal(2),x) != nothing
i = findfirst(isequal(2),x)
deleteat!(x,i)
elseif findfirst(isequal(3),x) != nothing
i = findfirst(isequal(3),x)
deleteat!(x,i)
end
The alternative here is to split the conditional into independent if end
blocks, when that is the same, with temporary itest
variables before each one:
itest = findfirst(isequal(2),x)
if itest != nothing
deleteat!(x,itest)
end
itest = findfirst(isequal(3),x)
if itest != nothing
deleteat!(x,itest)
end
For a one-liner, I arrived to this:
i = findfirst(isequal(2),x); i != nothing && deleteat!(x,i)
i = findfirst(isequal(3),x); i != nothing && deleteat!(x,i)
Is there a cleaner way to write this? Particularly in the case of elseif
statements, which are not necessarily the same thing as the multiple if end
blocks.