Julia for循环中的重载函数

Julia for循环中的重载函数,julia,Julia,假设我想要实现一个提供自定义向量类的模块,并为它重载所有基本的一元操作(round、ceil、floor等等)。这在朱莉娅身上应该很简单: 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(

假设我想要实现一个提供自定义向量类的模块,并为它重载所有基本的一元操作(round、ceil、floor等等)。这在朱莉娅身上应该很简单:

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
方法,因此这不是有效的解决方案

有一个很好的例子,可以说明您正在尝试做什么,循环符号以生成函数。以下是使循环正常工作的方法:

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))

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

如果您
导入Base.round、Base.ceil、Base.floor
,则可以省略
Base。
并编写
($f)(x::MyVector)=MyVector($f)(x.data))
,我认为函数重载的推荐样式是这样的。您也可以使用
导入基底:圆形、天花板、地板
导入高基底
,我更喜欢
@eval(Base.$f)
样式,因为我只需要在一个地方跟踪计算的符号。您的代码在版本
0.4+
0.5+
中运行良好,这个错误只发生在版本0.3.x中,我认为它是由语法歧义引起的,因为在版本
0.3.11
中使用括号解决了这个问题。