Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement