How do I define a function whose argument is iterable?

function printItems(iter)
#print or do something with each item
end

How do I say “iter” is of type that can be iterated on? I don’t want to say for example AbstractArray because anything iteratable will work.

Note: I do understand one can use other ways like foreach() etc.

But I am question is about the “type” of specifying something as “iterable” or “iteratable”

Or is that implied with “any”

Appreciate your time

I think a fruitful transform of your query would be: design a function that does its thing on a single item, and then use broadcast.

pr(x) = println("$x")
a = (1, 2, 3.0)
pr.(a)
1 Like

Thank you.

Ignore my function for a minute.

May be my direct question should be

“is there a base type that allows iteration”

Any collection can be iterated. Even non collections can implement iteration. Can a function specify such a constraint.

No, it should just be printitems(iter) accepting type ::Any.

1 Like

I understand that you can want to verify this so you can fail as soon as possible, what is often a good practice. The majority of the Julia code, however, will probably just receive Any and let the exception be raised if the object cannot be iterated.

Note, however, that, while @mcabbott is correct, i.e., there is no base type that allows iteration, you can write a conditional checking if the object allows iteration, you just check with applicable(iterate, object).

1 Like

There was some discussion of this recently here: What's the best way to dispatch on an _iterable_ trait?.

The TLDR is: yes, you can do this (and you can do it efficiently), but there’s probably a better way to get what you want.

1 Like