英文:
Julia: Expected Vector{Array{Float32}}, got a value of type Vector{Vector{Float32}}
问题
Sure, here's the translated code:
我有一个函数 `g`,它以 Float32 数组的 Vector 作为输入。但是,当我像下面这样调用该函数时,出现了一个错误,说找不到匹配 `g(::Vector{Vector{Float32}})` 的方法:
代码:
```julia
function g(x::Array{Array{Float32}, 1})
return x
end
function f()
a = [[1f0], [2f0]]
println( g(a) )
end
错误:
MethodError: no method matching g(::Vector{Vector{Float32}})
Closest candidates are:
g(::Vector{Array{Float32}}) at ~/.../runtests.jl:25
如何让 g
接受任意大小的 Float32 数组的向量作为输入,包括 1D 数组(向量)?我是 Julia 的新手,所以提前感谢您的帮助!
<details>
<summary>英文:</summary>
I have a function `g` that takes in a Vector of Float32 Arrays as input. However, when I call the function as follows, I get an error saying that no method matching `g(::Vector{Vector{Float32}})` was found:
Code:
function g(x::Array{Array{Float32}, 1})
return x
end
function f()
a = [[1f0], [2f0]]
println( g(a) )
end
Error:
MethodError: no method matching g(::Vector{Vector{Float32}})
Closest candidates are:
g(::Vector{Array{Float32}}) at ~/.../runtests.jl:25
How do I let `g` take in as input a vector of arbitrarily sized Float32 arrays, including 1D arrays (vectors)? I'm new to Julia, so thanks in advance for your help!
</details>
# 答案1
**得分**: 1
`x::Array{Array{Float32}, 1}` 不同于 `x::Array{Array{Float32, 1}, 1}` — 也就是说,您在声明参数类型时表示您的参数是一个包含*任意维度*数组的数组,这是一种具体类型,与包含*1维*数组的数组不同。
也许您想要的是:
```julia
function g(x::Array{<:Array{Float32}, 1})
或者等效地:
function g(x::Vector{<:Array{Float32}})
或者更一般地(例如):
function g(x::AbstractVector{<:AbstractArray{<:Real}})
以接受任何类型的1维数组(AbstractVector
的任何子类型),其元素是任何类型的任意维度的实数数组。
请参阅Julia FAQ 中的不变类型。
另请参阅Julia 手册中的参数类型声明。通常情况下,使用像 g(x::Array{Array{Float32, 1}, 1})
这样具体的类型签名来声明函数几乎没有性能优势,并且几乎肯定比必要的要不够通用。
英文:
x::Array{Array{Float32}, 1}
is different from x::Array{Array{Float32, 1}, 1}
— that is, you are saying that your argument is an array of arbitrary-dimension arrays, which is a specific type and is different from an array of 1d arrays.
You maybe want
function g(x::Array{<:Array{Float32}, 1})
or equivalently
function g(x::Vector{<:Array{Float32}})
or more generally (for example):
function g(x::AbstractVector{<:AbstractArray{<:Real}})
to accept any type of 1d array (any subtype of AbstractVector
) whose elements are any type of any-dimensional array of any type of real number.
See the Julia FAQ on invariant types.
See also the Julia manual on argument-type declarations. There is generally zero (nada, none, zip) performance advantage to declaring a function with a type signature as specific as g(x::Array{Array{Float32, 1}, 1})
, and it's almost certainly less general than necessary.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论