【问题标题】:Julia automatically generate functions and export themJulia 自动生成函数并导出它们
【发布时间】:2015-09-27 13:35:12
【问题描述】:

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

代码生成已经生效:

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

给我功能

maximumfilter
minimumfilter
...

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

export $(fname)

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

【问题讨论】:

  • eval(Expr(:export, fname)) 有效吗?我在SymPy 中使用了类似的东西。不确定这是不是最好的方法。
  • 谢谢,它对我有用!
  • @jverzani Tom 的回答很有趣,但由于(令人难以置信的)简单性以及它适用于 v1.0 的事实,您的评论可能应该是公认的答案。如果您发布它,那么我肯定会支持它。
  • 我认为这是旧版 julia 的问题,其中 Expr(:export, fname) == :(export $fname) 不成立。

标签: metaprogramming julia


【解决方案1】:

您可以考虑使用宏:

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 了解更多信息。

【讨论】:

  • 对我来说这不起作用,我在 export $(esc(fname)) 行得到了一个“语法:表达式结束后的额外标记”(“”)。
  • 你在 0.3 上吗?我使用的是 0.4 开发版本,因此自 0.3 以来语法可能/很可能发生了变化。我没有安装 0.3...其他人可以帮忙吗?
猜你喜欢
  • 2011-10-18
  • 2021-10-25
  • 1970-01-01
  • 1970-01-01
  • 2020-10-16
  • 2013-10-07
  • 2021-01-17
  • 1970-01-01
  • 2011-04-18
相关资源
最近更新 更多