gpt4 book ai didi

metaprogramming - Julia 自动生成函数并导出它们

转载 作者:行者123 更新时间:2023-12-03 22:41:22 25 4
gpt4 key购买 nike

我想自动生成一些函数并自动导出。举个具体的例子,假设我想构建一个模块,它提供接收信号并对其应用移动平均/最大值/最小值/中值的函数。

代码生成已经有效:

for fun in (:maximum, :minimum, :median, :mean)
fname = symbol("$(fun)filter")
@eval ($fname)(signal, windowsize) = windowfilter(signal, $fun, windowsize)
end

给我功能
maximumfilter
minimumfilter
...

但是如何自动导出它们?例如我想在上面的循环中添加一些代码,比如
export $(fname)

并在创建后导出每个函数。

最佳答案

您可以考虑使用宏:

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

当你加载它时,你会看到函数被自动导出:
julia> using filtersExample

julia> maximumfilter(1,2)
called from maximum: 1 2

julia> minimumfilter(1,2)
called from minimum: 1 2

the manual了解更多信息。

关于metaprogramming - Julia 自动生成函数并导出它们,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31313040/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com