Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create a method that takes any iterable collection of strings?

Tags:

julia

I have a function, f. I want to add a method that takes any container of Strings. For example, I want to write a method that generates the following when needed:

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

Is this possible to do in Julia's type system? Right now, I'm using a macro to write a specialized method when I need it.

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

This keeps things DRY, but it feels...wrong.

like image 806
jbn Avatar asked Aug 01 '15 13:08

jbn


People also ask

How do I iterate through collections?

There are three common ways to iterate through a Collection in Java using either while(), for() or for-each(). While each technique will produce more or less the same results, the for-each construct is the most elegant and easy to read and write.

How do I make a collection iterator?

Obtain an iterator to the start of the collection by calling the collection's iterator( ) method. Set up a loop that makes a call to hasNext( ). Have the loop iterate as long as hasNext( ) returns true. Within the loop, obtain each element by calling next( ).

How do I convert iterable to collections?

To convert iterable to Collection, the iterable is first converted into spliterator. Then with the help of StreamSupport. stream(), the spliterator can be traversed and then collected with the help collect() into collection.


2 Answers

Can't you just use duck typing? I.e., just assume that you're feeding the function an object of the right type and throw an error if at some point e.g. you don't have a string in your iterable.

This should improve once you can really talk about iterables using traits; currently there is no iterable type. Scott's answer, for example, will not work with a tuple of strings, even though that is 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"
like image 59
David P. Sanders Avatar answered Sep 18 '22 22:09

David P. Sanders


At least in Julia 0.4, the following should work:

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
like image 25
Scott Jones Avatar answered Sep 19 '22 22:09

Scott Jones