So, I can assert the output type of a function like this (trivial example for demo purposes)
f(x)::Int = x
However, what if the output type depends on an input type parameter
f(x::Vector{T})::T where T = x[1]
This produces an error and I don’t understand how I can assert the output type T
correctly here.
How can I assert that the output type of a function is the input parameter T
in general?
thofma
November 29, 2019, 8:26pm
2
I think this is a problem with the short function definition (https://github.com/JuliaLang/julia/issues/21847 and https://github.com/JuliaLang/julia/issues/31560 )
The long version works as expected:
julia> function f(x::T)::T where {T}
return x*1.0::T
end
f (generic function with 1 method)
julia> f(2)
ERROR: TypeError: in typeassert, expected Int64, got Float64
Stacktrace:
[1] f(::Int64) at ./REPL[4]:2
[2] top-level scope at none:0
1 Like
This seems to work:
julia> (f(x::Vector{T})::T) where {T} = x[1]
f (generic function with 1 method)
julia> f([3, 4])
3
2 Likes