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

Add only function #25078

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
3 changes: 3 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -436,6 +436,9 @@ Library improvements
defined, linear-algebra function `transpose`. Similarly,
`permutedims(v::AbstractVector)` will create a row matrix ([#24839]).

* New function `only(x)` returns the one-and-only element of a collection `x`, and throws
an error if `x` contains zero or multiple elements.

Compiler/Runtime improvements
-----------------------------

Expand Down
1 change: 1 addition & 0 deletions base/exports.jl
Original file line number Diff line number Diff line change
Expand Up @@ -813,6 +813,7 @@ export

enumerate, # re-exported from Iterators
zip,
only,

# object identity and equality
copy,
Expand Down
31 changes: 30 additions & 1 deletion base/iterators.jl
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@ import Base: start, done, next, isempty, length, size, eltype, iteratorsize, ite
using Base: tail, tuple_type_head, tuple_type_tail, tuple_type_cons, SizeUnknown, HasLength, HasShape,
IsInfinite, EltypeUnknown, HasEltype, OneTo, @propagate_inbounds, Generator, AbstractRange

export enumerate, zip, rest, countfrom, take, drop, cycle, repeated, product, flatten, partition
export enumerate, zip, rest, countfrom, take, drop, cycle, repeated, product, flatten,
partition, only

_min_length(a, b, ::IsInfinite, ::IsInfinite) = min(length(a),length(b)) # inherit behaviour, error
_min_length(a, b, A, ::IsInfinite) = length(a)
Expand Down Expand Up @@ -914,4 +915,32 @@ function next(itr::PartitionIterator, state)
return resize!(v, i), state
end

"""
only(x)

Returns the one and only element of collection `x`, and throws an error if the collection
has zero or multiple elements.
"""
Base.@propagate_inbounds function only(x)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems odd to mark this this way, where @inbounds only(x) is first(x)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The oddness here comes because I want @inbounds to propagate to next, since that can have @boundschecks in it.

i = start(x)
@boundscheck if done(x, i)
error("Collection is empty, must contain exactly 1 element")
end
(ret, i) = next(x, i)
@boundscheck if !done(x, i)
error("Collection has multiple elements, must contain exactly 1 element")
end
return ret
end

# Collections of known size
only(x::Tuple{}) = error("Tuple is empty, must contain exactly 1 element")
only(x::Tuple{Any}) = x[1]
only(x::Tuple) = error("Tuple contains $(length(x)) elements, must contain exactly 1 element")

only(a::AbstractArray{<:Any, 0}) = @inbounds return a[]

only(x::NamedTuple{<:Any, <:Tuple{Any}}) = first(x)
only(x::NamedTuple) = error("NamedTuple contains $(length(x)) elements, must contain exactly 1 element")

end
2 changes: 1 addition & 1 deletion base/sysimg.jl
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,7 @@ end
include("dict.jl")
include("set.jl")
include("iterators.jl")
using .Iterators: zip, enumerate
using .Iterators: zip, enumerate, only
using .Iterators: Flatten, product # for generators

# Definition of StridedArray
Expand Down
1 change: 1 addition & 0 deletions doc/src/stdlib/iterators.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,5 @@ Base.Iterators.flatten
Base.Iterators.partition
Base.Iterators.filter
Base.Iterators.reverse
Base.Iterators.only
```
22 changes: 22 additions & 0 deletions test/iterators.jl
Original file line number Diff line number Diff line change
Expand Up @@ -447,3 +447,25 @@ end
@test Iterators.reverse(Iterators.reverse(t)) === t
end
end

@testset "only" begin
@test only([3]) === 3
@test_throws ErrorException only([])
@test_throws ErrorException only([3, 2])

@test @inferred(only((3,))) === 3
@test_throws ErrorException only(())
@test_throws ErrorException only((3, 2))

@test only(Dict(1=>3)) === (1=>3)
@test_throws ErrorException only(Dict{Int,Int}())
@test_throws ErrorException only(Dict(1=>3, 2=>2))

@test only(Set([3])) === 3
@test_throws ErrorException only(Set(Int[]))
@test_throws ErrorException only(Set([3,2]))

@test @inferred(only((;a=1))) === 1
@test_throws ErrorException only(NamedTuple())
@test_throws ErrorException only((a=3, b=2.0))
end