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)
The following language constructs call convert : Assigning to an array converts to the array's element type. Assigning to a field of an object converts to the declared type of the field. Constructing an object with new converts to the object's declared field types.
Julia has an inbuilt parse method that allows conversion of string to numeric datatype. A string can be converted to the desired numeric datatype until it's an invalid string. We can also specify the base for conversion like decimal, binary, octal or hexadecimal.
In other words, the representable floating-point numbers are densest in the real number line near zero, and grow sparser exponentially as one moves farther away from zero. By definition, eps(1.0) is the same as eps(Float64) since 1.0 is a 64-bit floating-point value.
Every function in Julia is a generic function. A generic function is conceptually a single function, but consists of many definitions, or methods. The methods of a generic function are stored in a method table. Method tables (type MethodTable ) are associated with TypeName s.
There are two problems with your code:
+
only promote subtypes of Number
;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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With