Last active
September 24, 2016 19:28
-
-
Save jlapeyre/66c7714f22c66123add5db0accf1f01d to your computer and use it in GitHub Desktop.
`buildif` builds an if-elseif-else construct programmatically.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
doc""" | |
buildif(exprs...) | |
`buildif` builds an if-elseif-else construct programmatically. | |
`buildif` returns an expression equivalent to an if-elseif-else | |
construct, where, if the length of exprs is even, then the odd-indexed | |
elements of exprs are condition expressions and the even-indexed | |
elements are code blocks for the corresponding branches. If the length | |
of exprs is odd, then the last element is the default code block. In | |
the even case, the default is `nothing`. | |
```julia | |
if expr[1] | |
expr[2] | |
elseif expr[3] | |
expr[4] | |
else | |
expr[5] | |
end | |
``` | |
""" | |
function buildif(exprs...) | |
n = length(exprs) | |
n == 2 && return Expr(:if, exprs..., nothing) | |
n == 3 && return Expr(:if, exprs...) | |
ex = Expr(:if, exprs[1], exprs[2], nothing) | |
exargs = ex.args | |
for i in 3:2:(n-3) | |
newif = Expr(:if, exprs[i], exprs[i+1], nothing) | |
exargs[3] = newif | |
exargs = newif.args | |
end | |
if iseven(n) | |
exargs[3] = Expr(:if, exprs[n-1], exprs[n], nothing) | |
else | |
exargs[3] = Expr(:if, exprs[n-2], exprs[n-1], exprs[n]) | |
end | |
ex | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment