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

时间:2015-07-09 09:11:08

标签: metaprogramming julia

我想自动生成一些功能并自动导出。举一些具体的例子,假设我想建立一个模块,它提供了一个信号并将移动平均值/最大值/最小值/中值...应用于它的函数。

代码生成已经有效:

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

给我功能

maximumfilter
minimumfilter
...

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

export $(fname)

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

1 个答案:

答案 0 :(得分: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

加载后,您会看到自动导出的功能:

julia> using filtersExample

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

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

有关详细信息,请参阅the manual