官术网_书友最值得收藏!

Type conversions and promotions

The convert function can also be used explicitly in the code as convert(Int64, 7.0), which returns 7.

In general, convert(Type, x) will attempt to put the x value in an instance of Type. In most cases, type(x) will also do the trick, as in Int64(7.0), returning 7.

The conversion, however, doesn't always work:

  • When precision is lost—Int64(7.01)returns an ERROR: InexactError() error message
  • When the target type is incompatible with the source value—convert(Int64, "CV") returns an ERROR: MethodError: Cannot `convert` an object of type String to an object of type Int64 error message

This last error message really shows us how multiple dispatch works; the types of the input arguments are matched against the methods available for that function.

We can define our own conversions by providing new methods for the convert function. For example, for information on how to do this, refer to http://docs.julialang.org/en/latest/manual/conversion-and-promotion/#conversion.

Julia has a built-in system called automatic type promotion to promote arguments of mathematical operators and assignments to a common type: in 4 + 3.14, the integer 4 is promoted to a Float64 value, so that the addition can take place and results in 7.140000000000001. In general, promotion refers to the conversion of values of different types to one common type. This can be done with the promote function, which takes a number of arguments, and returns a tuple of the same values, converting them to a common type. An exception is thrown if promotion is not possible. Some examples are as follows:

  • promote(1, 2.5, 3//4) returns (1.0, 2.5, 0.75)
  • promote(1.5, im) returns (1.5 + 0.0im, 0.0 + 1.0im)
  • promote(true, 1.0) returns (1.0, 1.0)

Thanks to the automatic type promotion system for numbers, Julia doesn't have to define, for example, the + operator for any combinations of numeric types. Instead, it is defined as +(x::Number, y::Number) = +(promote(x,y)...).

It basically says: first, promote the arguments to a common type, and then perform the addition. Number is a common supertype for all values of numeric types. To determine the common promotion type of the two types, use promote_type(Int8, UInt16) to find whether it returns UInt16.

This is because, somewhere in the standard library, the following promote_rule function was defined as promote_rule(::Type{Int8}, ::Type{Uint16}) = UInt16.

You can take a look at how promoting is defined in the source code Julia in base/promotion.jl. These kinds of promotion rules can be defined for your own types too if needed.

主站蜘蛛池模板: 阳信县| 潜山县| 巫溪县| 大邑县| 玉门市| 图木舒克市| 砚山县| 青神县| 雷山县| 定州市| 永清县| 万山特区| 云和县| 霍州市| 阿图什市| 揭西县| 拜泉县| 刚察县| 连江县| 定兴县| 东平县| 南岸区| 平顺县| 三台县| 侯马市| 仁化县| 保康县| 乌什县| 井陉县| 巴林左旗| 永州市| 荥经县| 台中市| 西和县| 长葛市| 电白县| 剑河县| 土默特右旗| 阿图什市| 修水县| 乃东县|