10

At http://julia.readthedocs.org/en/latest/manual/conversion-and-promotion/, there is a discussion about adding integers to floats and so on, and and at the end it says

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.

From this I inferred that when defining my own numeric type, I simply needed to define how to convert it to a known type for it to 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) = 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)

1 Answer 1

15

There are two problems with your code:

  • arithmetic operators such as + only promote 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) = x.n

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

end
Sign up to request clarification or add additional context in comments.

4 Comments

Can you explain the difference between promotion and conversion?
convert tells the compiler how to perform the conversion from MyType to Int when it has been already decided to do so. promote_rule tells the compiler which conversion to perform when it sees both Int and MyType as operands — whether to convert MyType to Int or Int to MyType.
With your code I am getting ERROR: no promotion exists for MyType and Int64 in + at promotion.jl:158.
You likely need to restart the REPL, or use module qualification: m = Test.MyType(5); m+3. You may have a different notion of MyType already in your session.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.