Can multiple macros be used on one line?
Macros are analogous to functions for generating expressions at compile time. Just as functions map a tuple of argument values to a return value, macros map a tuple of argument expressions to a return expression. Macros are called with the following general syntax:
@name expr1 expr2 ... @name(expr1, expr2, ...)
Here's an example (albeit a bit pointless) using two well-known macros:
# This is an assert construct very similar to what you'd find in a language like
# C, C++, or Python. (This is slightly modified from the example shown in docs)
macro assert(ex)
return :($ex ? println("Assertion passed") # To show us that `@assert` worked
: error("Assertion failed: ", $(string(ex))))
end
# This does exactly what you expect to: time the execution of a piece of code
macro timeit(ex)
quote
local t0 = time()
local val = $ex
local t1 = time()
println("elapsed time: ", t1-t0, " seconds")
val
end
end
However, note these two successful (i.e. - don't throw any errors) call macros separately:
@assert factorial(5)>=0
@timeit factorial(5)
And now together:
@timeit @assert factorial(5)>=0
Since the rightmost macro did not throw an error, the above line returns the total time taken to execute factorial(5)
as well as the time taken to complete the statement combined.
However, it is important to note that if one of the macros fails, the execution of the other macros in the call stack will, of course, terminate (as it should):
# This will throw an error (because we explicitly stated that @assert should
# do so. As such, the rest of the code did not execute.
@timeit @assert factorial(5)<0
Again, this is a bit of a silly example, but illustrates the above points and solves your question.
source to share