Advertisement
Guest User

Untitled

a guest
Sep 24th, 2016
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.07 KB | None | 0 0
  1. doc"""
  2. buildif(exprs...)
  3.  
  4. `buildif` builds an if-elseif-else construct programmatically.
  5.  
  6. `buildif` returns an expression equivalent to an if-elseif-else
  7. construct, where, if the length of exprs is even, then the odd-indexed
  8. elements of exprs are condition expressions and the even-indexed
  9. elements are code blocks for the corresponding branches. If the length
  10. of exprs is odd, then the last element is the default code block. In
  11. the even case, the default is `nothing`.
  12.  
  13. ```julia
  14. if expr[1]
  15. expr[2]
  16. elseif expr[3]
  17. expr[4]
  18. else
  19. expr[5]
  20. end
  21. ```
  22. """
  23.  
  24. function buildif(exprs...)
  25. n = length(exprs)
  26. n == 2 && return Expr(:if, exprs..., nothing)
  27. n == 3 && return Expr(:if, exprs...)
  28. ex = Expr(:if, exprs[1], exprs[2], nothing)
  29. exargs = ex.args
  30. for i in 3:2:(n-3)
  31. newif = Expr(:if, exprs[i], exprs[i+1], nothing)
  32. exargs[3] = newif
  33. exargs = newif.args
  34. end
  35. if iseven(n)
  36. exargs[3] = Expr(:if, exprs[n-1], exprs[n], nothing)
  37. else
  38. exargs[3] = Expr(:if, exprs[n-2], exprs[n-1], exprs[n])
  39. end
  40. ex
  41. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement