Skip to content

Commit 2cc803b

Browse files
tpappStefanKarpinski
authored andcommitted
Add Base.allunique (#15914)
Allows testing if elements in a collection are distinct (when compared with isequal). Terminates early in case of repeated elements, has methods for collections which are by construction distinct. Also added tests. See discussion at issue #15803.
1 parent 2c26a0a commit 2cc803b

File tree

4 files changed

+42
-0
lines changed

4 files changed

+42
-0
lines changed

base/exports.jl

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -744,6 +744,7 @@ export
744744
# collections
745745
all!,
746746
all,
747+
allunique,
747748
any!,
748749
any,
749750
collect,

base/set.jl

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,27 @@ function unique(f::Callable, C)
141141
out
142142
end
143143

144+
"""
145+
allunique(itr)
146+
147+
Return `true` if all values from `itr` are distinct when compared with `isequal`.
148+
"""
149+
function allunique(C)
150+
seen = Set{eltype(C)}()
151+
for x in C
152+
if in(x, seen)
153+
return false
154+
else
155+
push!(seen, x)
156+
end
157+
end
158+
true
159+
end
160+
161+
allunique(::Set) = true
162+
163+
allunique{T}(r::Range{T}) = (step(r) != zero(T)) || (length(r) <= one(T))
164+
144165
function filter(f, s::Set)
145166
u = similar(s)
146167
for x in s

doc/stdlib/collections.rst

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -226,6 +226,12 @@ Iterable Collections
226226
227227
Returns an array containing one value from ``itr`` for each unique value produced by ``f`` applied to elements of ``itr``\ .
228228

229+
.. function:: allunique(itr)
230+
231+
.. Docstring generated from Julia source
232+
233+
Return ``true`` if all values from ``itr`` are distinct when compared with ``isequal``\ .
234+
229235
.. function:: reduce(op, v0, itr)
230236

231237
.. Docstring generated from Julia source

test/sets.jl

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -207,6 +207,20 @@ u = unique([1,1,2])
207207
@test unique(iseven, [5,1,8,9,3,4,10,7,2,6]) == [5,8]
208208
@test unique(n->n % 3, [5,1,8,9,3,4,10,7,2,6]) == [5,1,9]
209209

210+
# allunique
211+
@test allunique([])
212+
@test allunique(Set())
213+
@test allunique([1,2,3])
214+
@test allunique([:a,:b,:c])
215+
@test allunique(Set([1,2,3]))
216+
@test !allunique([1,1,2])
217+
@test !allunique([:a,:b,:c,:a])
218+
@test allunique(4:7)
219+
@test allunique(1:1)
220+
@test allunique(4.0:0.3:7.0)
221+
@test allunique(4:-1:5) # empty range
222+
@test allunique(7:-1:1) # negative step
223+
210224
# filter
211225
s = Set([1,2,3,4])
212226
@test isequal(filter(isodd,s), Set([1,3]))

0 commit comments

Comments
 (0)