Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is Julia's convert() used?

Tags:

julia

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)
like image 380
asmeurer Avatar asked Oct 27 '14 18:10

asmeurer


People also ask

What is convert in Julia?

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.

What does Julia parse do?

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.

What does Float64 mean in Julia?

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.

What is the type of a function in Julia?

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.


1 Answers

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
like image 144
jch Avatar answered Sep 20 '22 08:09

jch