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

时间:2015-08-01 13:58:03

标签: julia

我有一个函数f。我想添加一个采用String s容器的方法。例如,我想编写一个在需要时生成以下内容的方法:

f(xs::Array{String, 1}) = ...
f(xs::DataArray{String, 1}) = ...
f(xs::ITERABLE{String}) = ...

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

@make_f(Array{String, 1})
@make_f(DataArray{String, 1})

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

2 个答案:

答案 0 :(得分:6)

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

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

E.g。

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"

答案 1 :(得分:3)

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

julia> abstract Iterable{T} <: AbstractVector{T}

julia> f{T<:Union{Vector{String},Iterable{String}}}(xs::T) = 1
f (generic function with 1 method)

julia> x = String["a", "é"]
2-element Array{AbstractString,1}:
 "a"
 "é"

julia> f(x)
1
相关问题