Thank you for your analysis! It’s a very accurate analysis of my problem. There, I think this is the crux of the problem:
That said, it seems that handling this dispatch at the level of func
might be better. I would imagine that the preparatory work also depends on whether you plan to produce one or many plots.
No, that’s not the case and that is the point! I wrote the original code for a single plot. Then I’m trying to extend it for multiple plots, just to loop over the values of x
, changing the filename from myfig.png
to myfig-p001.png
, . . . That’s the only difference.
My problem is that simple and the solutions everybody proposes are overkill.
I’m not against your solutions in general. I would write such code as everybody proposes if the two cases are different enough. I’m not saying that branching on whether the value is scalar or not is a superior solution in general. In most cases, dispatch is the superior solution.
If I write two functions to handle each cases separately, I would have to pass a lot of arguments to them from my preparatory code. I don’t think that extra complexity is worth it for my problem at hand.
If my code further extends and if the two cases (collection vs scalar) become different enough, then two separate functions would start to make sense. I don’t think, however, that it makes sense to do so just to avoid branching on whether the value is a collection or a scalar.
we don’t have a universal trait (much less a branch in the type hierarchy) to determine the iterability of an object. Whether something should be iterated or treated as a scalar is context-dependent so we could never hope to answer the question accurately and decisively.
Okay.
For example, should a String be treated as a monolithic object or as a ordered collection of characters? Should a vector be treated as a single object (perhaps representing a single point in N-dimensional space?) or as a collection of numbers? It makes no sense to sort the
(x, y, z) coordinates of a point but it’s entirely reasonable to sort a list of prices.
You explain why we cannot determine, in the current Julia, whether a value can be considered iterable or not. But, in the preceding paragraph you mentioned “trait”, and that approach isn’t impossible in principle. For example, the language designer could declare Vector
to be a subtype of Iterable
. Then, any Vector
would have to behave like an Iterable
in a context where a Iterable
is expected. The language designer could decide that String
is not an Iterable
and then a String
would not work as an Iterable
and you would have to write for c in iter(a_string)
to extract each character. And so on and so forth.
But, I’m sure that the Julia designers had good reasons not to take this approach.