Why are the types in this example different?

f0(x :: Float32) = 1f0

f1(p :: Float32) = function(x :: Float32);
return (x+p)
end

println(typeof([f0,f1(1.0f0)]))
println(typeof([f1(0.0f0),f1(1.0f0)]))

this results in
Vector{Function}
Vector{var"#1#2"{Float32}}

why? And:

function foo(v::Vector{Function})
println(“foo with Vector{Function}”)
end

function foo(v::Vector{Any})
println(“foo with Vector{Any}”)
end

foo([f0,f1(1.0f0)])
foo([f1(0.0f0),f1(1.0f0)])

results in
foo with Vector{Function}
ERROR: LoadError: MethodError: no method matching foo(::Vector{var"#1#2"{Float32}})

Again: why? and how tow fix the foo function so that foo([f1(0.0f0),f1(1.0f0)]) works (wtihout using convert in the function call)?

Tanks.

To your first question:

julia> typeof(f1(1f0)) == typeof(f1(0f0))
true

julia> typeof(f1(1f0)) == typeof(f0)
false

The [] tries to create a vector of the smallest possible type, and with all f1 functions it can use this type. f0 is of a different type (as all functions are their own type) so it has to punt to the supertype. This is the same as:

julia> typeof([sin, sin])
Vector{typeof(sin)} 

julia> typeof([sin, cos])
Vector{Function} 

On your second question you are probably looking for

julia> function foo(v::Vector{<:Any})
       println("foo with Vector{Any}")
       end
foo (generic function with 3 methods)

julia> foo([f1(0.0f0),f1(1.0f0)])
foo with Vector{Any}

(unrelated, but it’s very helpful to enclose your code in triple backticks ``` to make it more legible and ensure quotation marks are faithfully represented)

2 Likes