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

RFC: exportable tuple-manipulation utilities #20370

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions base/exports.jl
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,8 @@ export
Range,
RangeIndex,
Rational,
ReferenceBack,
ReferenceFront,
Regex,
RegexMatch,
RemoteChannel,
Expand Down
36 changes: 36 additions & 0 deletions base/tuple.jl
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,42 @@ function _front(out, v, t...)
_front((out..., v), t...)
end

abstract ReferenceTuple
immutable ReferenceFront{TT<:Tuple} <: ReferenceTuple
t::TT
end
immutable ReferenceBack{TT<:Tuple} <: ReferenceTuple
t::TT
end

"""
split(t, ReferenceFront(ref)) -> front, back

Splits a tuple or CartesianIndex `t` into two pieces, `front` and
`back`, such that `t == (front..., back...)`. `front` has the same
length as the reference `ref`.
"""
split(t::Tuple, ref::ReferenceFront) = _splitfront((), t, ref.t)
_splitfront{N}(out::NTuple{N}, t, ref::NTuple{N}) = out, t
_splitfront(out, ::Tuple{}, ref) =
(@_noinline_meta; throw(DimensionMismatch("front reference had $(length(ref)) elements, but input had only $(length(out))")))
_splitfront(out, t, ref) =
(@_inline_meta; _splitfront((out..., t[1]), tail(t), ref))

"""
split(t, ReferenceBack(ref)) -> front, back

Splits a tuple or CartesianIndex `t` into two pieces, `front` and
`back`, such that `t == (front..., back...)`. `front` has the same
length as the reference `ref`.
"""
split(t::Tuple, ref::ReferenceBack) = _splitback((), t, ref.t)
_splitback{N}(out, t::NTuple{N}, ref::NTuple{N}) = out, t
_splitback(out, ::Tuple{}, ref) =
(@_noinline_meta; throw(DimensionMismatch("back reference had $(length(ref)) elements, but input had only $(length(out))")))
_splitback(out, t, ref) =
(@_inline_meta; _splitback((out..., t[1]), tail(t), ref))

## mapping ##

"""
Expand Down
3 changes: 3 additions & 0 deletions test/tuple.jl
Original file line number Diff line number Diff line change
Expand Up @@ -231,3 +231,6 @@ end
@test Tuple{Int,Vararg{Any}}(Float64[1,2,3]) === (1, 2.0, 3.0)
@test Tuple(ones(5)) === (1.0,1.0,1.0,1.0,1.0)
@test_throws MethodError convert(Tuple, ones(5))

@test @inferred(split((1,2,3), ReferenceFront((5,5)))) === ((1,2), (3,))
@test @inferred(split((1,2,3), ReferenceBack((5,5)))) === ((1,), (2,3))