Extracting Array element type for subsequent use

I want to do something like:

function foo(x::Array{T,1}, y::Array{T,1})
  n1 = length(x)
  n2 = length(y)
  z = zeros(T, n1+n2)
  ...
end

First problem is that I actually need to write

function foo(x::Array{T,1} where T, y::Array{T,1} where T)
...

But then the subsequent use of T gives me an UndefVarError.

1 Like

Use:

function foo(x::Array{T,1}, y::Array{T,1}) where T
...
1 Like
function foo{T}(x::Array{T,1}, y::Array{T,1})

i think you meant the above .

what you wrote will give you a different T for every value in the arrays I think.

That did it, Thank you !

function foo{T}(x::Array{T,1}, y::Array{T,1}) zeros(T,length(x)+length(y)) end
foo (generic function with 1 method)

julia> foo(rand(10), rand(5))
15-element Array{Float64,1}:
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0
0.0

julia>

This syntax is going to be removed. Use the where version instead.

3 Likes

That’s the old syntax, @fredrikekre was correct for v0.6 and later.
That doesn’t not mean that the elements of the Vectors can have a different type, that would be:

function foo(x::Vector{Any}, y::Vector{Any})

The following means that both x and y have to have the same element type (which can be Any)

function foo(x::Vector{T}, y::Vector{T}) where T
1 Like

I’ll also point out: if you declare a function like this: function foo(x::Vector{T} where T), you can still obtain the element type of x in the function body using the eltype() function even though you can’t get it from T.

1 Like

Yes, and there’s even a nice short form:
function foo(x::Vector{<:Any})

The signature should be defined as: foo(x::Vector{T}) where {T} instead.

Notice you are indeed able to get the type of the Vector from T as well as from eltype(x), ie.:

julia> function foo(x::Vector{T}) where {T}
           @show(T, T == eltype(x))
           return nothing
       end
foo (generic function with 1 method)

julia> a = rand(5);

julia> b = rand(Int, 5);

julia> foo(a)
T = Float64
T == eltype(x) = true

julia> foo(b)
T = Int64
T == eltype(x) = true