JuliaArrays / ReadOnlyArrays.jl

A wrapper type around AbstractArray that is read-only
Other
27 stars 5 forks source link

Easy-to-use macro? #10

Open MilesCranmer opened 3 months ago

MilesCranmer commented 3 months ago

Just wondering if anybody would be interested in the following macro @bkamins @markmbaum?

A function would be fine too of course; it just feels a bit more appropriate as a macro due to the behavior as both an operation on types and on instances.

macro readonly(expr)
    esc(:($(_readonly)($expr)))
end
_readonly(::Type{A}) where {T,N,A<:AbstractArray{T,N}} = ReadOnlyArray{T,N,A}
_readonly(ar::AbstractArray) = ReadOnlyArray(ar)

The use-cases are as follows:

julia> @readonly Vector{UInt8}
ReadOnlyArray{UInt8, 1, Vector{UInt8}}

julia> @readonly Array{Float32, 3}
ReadOnlyArray{Float32, 3, Array{Float32, 3}}

julia> @readonly [1, 2, 3]
3-element ReadOnlyArray{Int64, 1, Vector{Int64}}:
 1
 2
 3

I've got it as an internal macro but I could just upstream it here if interested.

MilesCranmer commented 3 months ago

Actually changed my mind... A readonly function is better than a macro. But I think an easy to use function for MyArrayType{T,N} -> ReadOnlyArray{T,N,MyArrayType{T,N}} would be a huge help for readability.

bkamins commented 3 months ago

How would you want the function to work (i.e. how would it be different from what we have now with ReadOnlyArray)?

MilesCranmer commented 3 months ago

ReadOnlyArray is okay for construction, albeit a bit verbose.

The more useful thing is the type alias. It’s very wordy to type out the whole parametrized ReadOnlyArray.