2014-10-27 78 views
6

http://julia.readthedocs.org/en/latest/manual/conversion-and-promotion/,有一个关于添加整数花车等的讨论,并在最后它说何时使用Julia的convert()?

User-defined types can easily participate in this promotion system by defining methods for conversion to and from other types, and providing a handful of promotion rules defining what types they should promote to when mixed with other types.

由此我推断,定义自己的数字类型时,我只是需要确定如何将其转换为已知类型,以便与其上的功能一起使用。但我想这和它似乎并没有工作:

julia> type MyType 
      n::Int 
     end 

julia> convert(::Type{Int}, x::MyType) = x.n 
convert (generic function with 1 method) 

julia> convert(Int, MyType(1)) 
1 

julia> MyType(1) + 1 
ERROR: `+` has no method matching +(::MyType, ::Int64) 

回答

7

有两个问题与您的代码:

  • 算术运算符,如+只有促进Number亚型;
  • 您需要定义除转换函数之外的升级规则。

以下应该做你想要什么:

module Test 

import Base: convert, promote_rule 

type MyType <: Number 
    n :: Int 
end 

convert(::Type{Int}, x::MyType) = x.n 

promote_rule(::Type{MyType}, ::Type{Int}) = Int 

end 
+0

你能解释的推广和转化之间的区别? – asmeurer 2014-10-27 19:21:01

+5

'convert'告诉编译器在已经决定如何执行从'MyType'到'Int'的转换。 'promote_rule'告诉编译器当它将'Int'和'MyType'作为操作数时执行哪个转换 - 是否将MyType转换为Int或将Int转换为MyType。 – jch 2014-10-27 19:35:12

+0

使用您的代码,我得到了'错误:MyType和Int64 in + at promotion.jl:158'不存在促销。 – asmeurer 2014-10-28 01:29:15