Macros 可以在一行上使用多个宏吗?
有人知道是否可以对一行使用多个宏吗?比如说,Macros 可以在一行上使用多个宏吗?,macros,julia,callstack,Macros,Julia,Callstack,有人知道是否可以对一行使用多个宏吗?比如说, @devec,@inbounds[expr] 宏是表达式生成的函数的类似物 编译时。正如函数将参数值的元组映射到 返回值,宏将参数表达式的元组映射到返回的 表情。使用以下通用语法调用宏: 下面是一个使用两个著名宏的示例(尽管有点荒谬): # This is an assert construct very similar to what you'd find in a language like # C, C++, or Python. (This
@devec,@inbounds[expr]
宏是表达式生成的函数的类似物
编译时。正如函数将参数值的元组映射到
返回值,宏将参数表达式的元组映射到返回的
表情。使用以下通用语法调用宏:
下面是一个使用两个著名宏的示例(尽管有点荒谬):
# 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
但是,请分别注意这两个成功的(即-不抛出任何错误)宏调用:
@assert factorial(5)>=0
@timeit factorial(5)
现在我们一起:
@timeit @assert factorial(5)>=0
由于最右边的宏没有引发错误,因此上行将返回执行factorial(5)
所花费的总时间以及执行断言所花费的时间
但是,需要注意的重要一点是,当其中一个宏失败时,调用堆栈中其他宏的执行当然会终止(应该如此):
#这将抛出一个错误(因为我们明确声明@assert应该
#因此,代码的其余部分没有执行。
@timeit@assert阶乘(5)
@timeit @assert factorial(5)>=0
# 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