# Extracting Array element type for subsequent use

#1

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.

#2

Use:

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

#3
``````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.

#4

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>

#5

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

#6

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``

#7

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`.

#8

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

#9

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
``````