Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

similar should accept a type as first parameter #17124

Closed
eschnett opened this issue Jun 26, 2016 · 3 comments
Closed

similar should accept a type as first parameter #17124

eschnett opened this issue Jun 26, 2016 · 3 comments

Comments

@eschnett
Copy link
Contributor

The function similar accepts a container as first parameter, but not a container type, in the same way as e.g. eltype. (If dims is not specified, it should then construct an empty container.)

In some cases, for example in distributed computing, one wants to allocate a container to hold the result of a map-like calculation, without having access to the original container. However, the type of the original container is known, as well as the element type of the result. In this case, the interface offered by similar is insufficient -- it does not allow allocating a new container without creating an empty dummy container from the type.

A fall-back definition that could be added to Base is

similar{CT}(::Type{CT}, specs...) = similar(CT(), specs...)

although I assume that many container types will want to provide a more specialized version that avoid creating an empty container.

@timholy
Copy link
Member

timholy commented Jun 26, 2016

The new allocate_for (from #16260) will likely be renamed similar (see #16973), which will do mostly what you're suggesting here. From your call, what's missing is the "reference array"; from the standpoint of #16260, I have previously had concerns about omitting it, because I want to support multiple co-existing packages that use unconventional indexing. However, what Jeff proposed as UpTo will likely solve that problem (each package could define its own range type), so the reference array may no longer be required.

@nalimilan
Copy link
Member

In the long-term, the fallback should likely go the other way:

similar{CT}(::CT, specs...) = similar(CT, specs...)

@timholy
Copy link
Member

timholy commented Jun 27, 2016

We also need to support this type of call:

similar(dims->zeros(Int, dims), shape)

which allocates an all-zero array (lower-case array, not Array) whose indices are determined by the types in shape.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants