New package TypeUtils
provides useful methods to deal with types in Julia.
Cast value to type
The method, as
is designed to cast a value to a given type. The name was inspired by the built-in Zig function @as
.
A first usage is:
as(T, x)
which yields x
converted to type T
. This behaves like a lazy version of convert(T,x)::T
doing nothing if x
is already of type T
and performing the conversion and the type assertion otherwise.
By default, the as
method calls convert
only if needed but also implements a number of conversions not supported by convert
. The as
method is therefore a bit more versatile than convert
while relaxing the bother to remember which function or constructor to call to efficiently perform the intended conversion. For example:
julia> as(Tuple, CartesianIndex(1,2,3)) # yields tuple of indices
(1, 2, 3)
julia> as(CartesianIndex, (1,2,3)) # calls constructor
CartesianIndex(1, 2, 3)
julia> as(Tuple, CartesianIndices(((-2:5), (1:3)))) # yields tuple of index ranges
(-2:5, 1:3)
julia> as(CartesianIndices, ((-2:5), (1:3))) # calls constructor
CartesianIndices((-2:5, 1:3))
julia> as(String, :hello) # converts symbol to string
"hello"
julia> as(Symbol, "hello") # converts string to symbol
:hello
Another usage is:
as(T)
which yields a callable object that converts its argument to type T
. This can be useful with map
. For instance:
map(as(Int), dims)
to convert dims
to a tuple (or array) of Int
s.
Additional conversions becomes possible if another package such as TwoDimensonal
is loaded.
Parameter-less type
The call:
parameterless(T)
yields the type T
without parameter specifications. For example:
julia> parameterless(Vector{Float32})
Array
Deal with array element types
The TypeUtils
package provides a few methods to deal with array element types:
-
promote_eltype(args...)
yields the promoted element type of the argumentsargs...
which may be anything implementing theeltype
method. -
convert_eltype(T,A)
yields an array with the same entries asA
except that their type isT
. -
as_eltype(T,A)
yields an array which lazily converts its entries to typeT
. This can be seen as a memory-less version ofconvert_eltype(T,A)
. The methodas_eltype
is similar to the methodof_eltype
provided by theMappedArrays
package.
Methods convert_eltype(T,A)
and as_eltype(T,A)
just return A
itself if its elements are of type T
.
Type of result returned by a function
The call:
g = as_return(T, f)
yields a callable object such that g(args...; kwds...)
lazily converts the value returned by f(args...; kwds...)
to the type T
. Methods return_type(g)
and parent(g)
can be used to respectively retrieve the type T
and the original function f
. A similar kind of object be built with the composition operator:
g = as(T)∘f
The method return_type
may also be used as:
T = return_type(f, argtypes...)
to infer the type T
of the result returned by f
when called with arguments of types argtypes...
.