Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use multiple macros on a single line?

Does any know whether it is possible to use multiple macros for a single line? For example,

@devec, @inbounds [expr]

like image 414
sjnahn Avatar asked Sep 05 '25 03:09

sjnahn


1 Answers

Yes, you can, since:

Macros are the analogue of functions for expression generation 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 returned expression. Macros are invoked with the following general syntax:

@name expr1 expr2 ...
@name(expr1, expr2, ...)

Here's an example (albeit a slightly nonsensical one) utilizing 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. - do not throw any errors) macro calls separately:

@assert factorial(5)>=0
@timeit factorial(5)

And, now together:

@timeit @assert factorial(5)>=0

Because the right-most macro did not raise an error, the above line returns the total time it took to execute the factorial(5) as well as the time to perform the assertion, combined.

However, the important thing to note is that when one of the macros fail, execution of the other macros in the call stack are of course terminated (as it should be):

# 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, it's a bit of a silly example, but illustrates the above points and addresses your question.

like image 105
jrd1 Avatar answered Sep 07 '25 23:09

jrd1