如何创建一个采用任何可迭代字符串集合的方法?

jbn*_*jbn 5 julia

我有一个功能,f.我想添加一个方法来获取任何容器的Strings.例如,我想编写一个在需要时生成以下内容的方法:

f(xs::Array{String, 1}) = ...
f(xs::DataArray{String, 1}) = ...
f(xs::ITERABLE{String}) = ...
Run Code Online (Sandbox Code Playgroud)

朱莉娅的类型系统可以做到这一点吗?现在,我正在使用宏来在需要时编写专门的方法.

@make_f(Array{String, 1})
@make_f(DataArray{String, 1})
Run Code Online (Sandbox Code Playgroud)

这让事情变得干涩,但感觉......错了.

Dav*_*ers 6

你不能只用鸭子打字吗?即,假设您正在为函数提供正确类型的对象并在某些时候抛出错误,例如您的迭代中没有字符串.

一旦你真正谈论使用特征的迭代,这应该会改善; 目前没有可迭代类型.例如,斯科特的答案不适用于字符串元组,即使它是可迭代的.

例如

julia> f(x) = string(x...)  # just concatenate the strings
f (generic function with 1 method)

julia> f(("a", "á"))
"aá"

julia> f(["a", "á"])
"aá"

julia> f(["a" "b"; "c" "d"])  # a matrix of strings!
"acbd"
Run Code Online (Sandbox Code Playgroud)


Sco*_*nes 3

至少在 Julia 0.4 中,以下内容应该有效:

\n\n
julia> abstract Iterable{T} <: AbstractVector{T}\n\njulia> f{T<:Union{Vector{String},Iterable{String}}}(xs::T) = 1\nf (generic function with 1 method)\n\njulia> x = String["a", "\xc3\xa9"]\n2-element Array{AbstractString,1}:\n "a"\n "\xc3\xa9"\n\njulia> f(x)\n1\n
Run Code Online (Sandbox Code Playgroud)\n