【问题标题】:Overload function in for loopfor循环中的重载函数
【发布时间】:2015-10-06 18:31:44
【问题描述】:

假设我想实现一个模块,提供一个自定义向量类并为它重载所有基本的一元操作(round、ceil、floor,...)。这在 Julia 中应该相当简单:

module MyVectors
export MyVector
immutable MyVector{T} data::Vector{T} end

# This is the tricky part
for f in (:round, :ceil, :floor)
    @eval Base.$f(x::MyVector) = MyVector($f(x.data))
end

end

很遗憾,这不起作用。我收到以下错误:

ERROR: error compiling anonymous: syntax: prefix $ in non-quoted expression
 in include at ./boot.jl:245
 in include_from_node1 at ./loading.jl:128
while loading /home/masdoc/Desktop/Julia Stuff/MyVectors.jl, in expression starting on line 6

问题似乎出在Base.$f 部分,因为如果我删除Base.,它就会编译。但是,我想重载 Base.round 而不是创建新的 round 方法,所以这不是一个有效的解决方案。

【问题讨论】:

  • 您的代码在0.4+0.5+ 版本中工作正常,此错误仅在版本0.3.x 中发生,我认为这是由语法歧义引起的,因为使用括号解决了版本@ 中的此问题987654329@.

标签: julia


【解决方案1】:

Requests.jl 可能是您尝试做的一个很好的例子,循环符号以生成函数。以下方法可让您的循环正常工作:

module MyVectors
export MyVector
immutable MyVector{T} data::Vector{T} end

# This is the tricky part
for f in (:round, :ceil, :floor)
    @eval (Base.$f)(x::MyVector) = MyVector(($f)(x.data))
end

end

using MyVectors
v = MyVector([3.4, 5.6, 6.7])

println(round(v))
println(ceil(v))
println(floor(v))

您可能还会发现 this julia 中有关元编程和宏的视频很有用。

【讨论】:

  • 另外如果你import Base.round, Base.ceil, Base.floor那么你可以省略Base.而写($f)(x::MyVector) = MyVector(($f)(x.data)),我认为推荐的函数重载样式是这样的。
  • 您也可以使用import Base: round, ceil, floorimportall Base,我更喜欢@eval (Base.$f) 样式,因为这样我只需在一个地方跟踪评估的符号。
猜你喜欢
  • 1970-01-01
  • 2013-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-03-04
  • 2019-07-15
  • 1970-01-01
相关资源
最近更新 更多