When is Julia convert () used?

Http://julia.readthedocs.org/en/latest/manual/conversion-and-promotion/ discusses adding integers to float, etc., and in the end he says

Custom types can easily participate in this promotion system by defining methods for converting to and from other types, and by providing several promotion rules that determine which types they should be promoted to when they are mixed with other types.

From this, I suggested that when defining my own numeric type, I just needed to determine how to convert it to a known type so that it would work with functions on it. But I tried this and it doesn't seem to work:

julia> type MyType n::Int end julia> convert(::Type{Int}, x::MyType) = xn convert (generic function with 1 method) julia> convert(Int, MyType(1)) 1 julia> MyType(1) + 1 ERROR: `+` has no method matching +(::MyType, ::Int64) 
+6
source share
1 answer

There are two problems in the code:

  • arithmetic operators such as + only support subtypes of Number ;
  • you need to define a promotion rule in addition to the conversion function.

The following should do what you want:

 module Test import Base: convert, promote_rule type MyType <: Number n :: Int end convert(::Type{Int}, x::MyType) = xn promote_rule(::Type{MyType}, ::Type{Int}) = Int end 
+7
source

Source: https://habr.com/ru/post/977293/


All Articles