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

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.

主站蜘蛛池模板: 永泰县| 普安县| 太白县| 日照市| 门源| 观塘区| 海林市| 黄山市| 荣成市| 金山区| 靖安县| 新乡县| 沛县| 双辽市| 龙胜| 庆城县| 汕尾市| 甘肃省| 柳州市| 西丰县| 巴彦淖尔市| 大同县| 廉江市| 长治县| 临沂市| 深州市| 台前县| 绥德县| 靖宇县| 德安县| 施秉县| 夏河县| 夏邑县| 隆昌县| 三河市| 沂水县| 公安县| 汉寿县| 夹江县| 于田县| 西华县|