Jan*_*ner 9 metaprogramming julia
我想自动生成一些函数并自动导出它们.举一些具体的例子,假设我想构建一个模块,它提供接收信号并应用移动平均值/最大值/最小值/中值...的函数.
代码生成已经有效:
for fun in (:maximum, :minimum, :median, :mean)
fname = symbol("$(fun)filter")
@eval ($fname)(signal, windowsize) = windowfilter(signal, $fun, windowsize)
end
Run Code Online (Sandbox Code Playgroud)
给我功能
maximumfilter
minimumfilter
...
Run Code Online (Sandbox Code Playgroud)
但是如何自动导出它们?例如,我想在上面的循环中添加一些代码
export $(fname)
Run Code Online (Sandbox Code Playgroud)
并在创建后导出每个函数.
小智 5
您可以考虑使用宏:
module filtersExample
macro addfilters(funs::Symbol...)
e = quote end # start out with a blank quoted expression
for fun in funs
fname = symbol("$(fun)filter") # create your function name
# this next part creates another quoted expression, which are just the 2 statements
# we want to add for this function... the export call and the function definition
# note: wrap the variable in "esc" when you want to use a value from macro scope.
# If you forget the esc, it will look for a variable named "maximumfilter" in the
# calling scope, which will probably give an error (or worse, will be totally wrong
# and reference the wrong thing)
blk = quote
export $(esc(fname))
$(esc(fname))(signal, windowsize) = windowfilter(signal, $(esc(fun)), windowsize)
end
# an "Expr" object is just a tree... do "dump(e)" or "dump(blk)" to see it
# the "args" of the blk expression are the export and method definition... we can
# just append the vector to the end of the "e" args
append!(e.args, blk.args)
end
# macros return expression objects that get evaluated in the caller's scope
e
end
windowfilter(signal, fun, windowsize) = println("called from $fun: $signal $windowsize")
# now when I write this:
@addfilters maximum minimum
# it is equivalent to writing:
# export maximumfilter
# maximumfilter(signal, windowsize) = windowfilter(signal, maximum, windowsize)
# export minimumfilter
# minimumfilter(signal, windowsize) = windowfilter(signal, minimum, windowsize)
end
Run Code Online (Sandbox Code Playgroud)
当你加载它时,你会看到自动导出的功能:
julia> using filtersExample
julia> maximumfilter(1,2)
called from maximum: 1 2
julia> minimumfilter(1,2)
called from minimum: 1 2
Run Code Online (Sandbox Code Playgroud)
有关详细信息,请参阅手册.
归档时间: |
|
查看次数: |
978 次 |
最近记录: |