EltypeExtensions.jl is a mini toolbox for eltype-related conversions. The motivation of this package comes from manipulating (nested) arrays with different eltypes. However if you have any reasonable idea that works on other instances, feel free to write an issue/pull request.
We note that this package has some overlap with TypeUtils.jl and Unitless.jl.
elconvert(T, x) works like convert(T, x), except that T refers to the eltype of the result. This can be useful for generic codes.
It should be always true that elconvert(T, x) isa _to_eltype(T, typeof(x)). However, since elconvert and _to_eltype use different routines, it's possible that the equality doesn't hold for some types. Please submit an issue or PR if that happens.
If typeof(x) is not in Base or stdlib, the package who owns the type should implement corresponding _to_eltype or elconvert. elconvert has fallbacks, in which case it could be unnecessary:
- For a subtype of
AbstractArray,elconvertcalls the constructorAbstractArray{T}and_to_eltypereturnsArray. - For a subtype of
AbstractUnitRange,elconvertcalls the constructorAbstractUnitRange{T}. - For a subtype of
AbstractRange,elconvertuses broadcast throughmap. - For a
Tuple,elconvertuses dot broadcast. - For other types,
elconvertcallsconvertand_to_eltype.
However, _to_eltype must be implemented for each type to support baseconvert and precisionconvert. The following types from Base and stdlib are explicitly supported by _to_eltype:
AbstractArray, AbstractDict, AbstractSet, Adjoint, Bidiagonal, BitArray,
CartesianIndices, Diagonal, Dict, Hermitian, Set, StepRangeLen, Symmetric,
SymTridiagonal, Transpose, TwicePrecision, UnitRange
The basetype is used for nested collections, where eltype is repeatedly applied until the bottom. precisiontype has a similar idea, but goes deeper when possible. precisiontype is used to manipulate the accuracy of (nested) collections.
sometype(T)gets thesometypeof typeT.sometype(x) = sometype(typeof(x))is also provided for convenience._to_sometype(T,S)converts the typeSto have thesometypeofT.someconvert(T,A)convertsAto have thesometypeofT.
where some can be el, base and precision.
precisionconvert accepts an optional third argument prec.
- When
Thas static precision,prechas no effect. - When
Thas dynamic precision,precspecifies the precision of conversion. Whenprecis not provided, the precision is decided by the external setup fromT. The difference is significant whenprecisionconvertis called by another function. See the document for an example. - When
Tis an integer, the conversion will dig intoRationalas well. In contrast, sinceRationalas a whole is more "precise" than an integer,precisiontypedoesn't unwrapRational.