Skip to content

Commit cbae586

Browse files
authored
Merge pull request #18533 from TotalVerb/fw/take-take
Make take and drop type-idempotent, and canonicalize their order
2 parents 98e29ed + b04c0fc commit cbae586

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

base/iterator.jl

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -338,6 +338,7 @@ julia> collect(take(a,3))
338338
```
339339
"""
340340
take(xs, n::Int) = Take(xs, n)
341+
take(xs::Take, n::Int) = Take(xs.xs, min(n, xs.n))
341342

342343
eltype{I}(::Type{Take{I}}) = eltype(I)
343344
iteratoreltype{I}(::Type{Take{I}}) = iteratoreltype(I)
@@ -391,6 +392,8 @@ julia> collect(drop(a,4))
391392
```
392393
"""
393394
drop(xs, n::Int) = Drop(xs, n)
395+
drop(xs::Take, n::Int) = Take(drop(xs.xs, n), max(0, xs.n - n))
396+
drop(xs::Drop, n::Int) = Drop(xs.xs, n + xs.n)
394397

395398
eltype{I}(::Type{Drop{I}}) = eltype(I)
396399
iteratoreltype{I}(::Type{Drop{I}}) = iteratoreltype(I)

test/functional.jl

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,21 @@ end
155155
@test Base.iteratorsize(drop(countfrom(1),3)) == Base.IsInfinite()
156156
@test_throws MethodError length(drop(countfrom(1), 3))
157157

158+
# double take
159+
# and take/drop canonicalization
160+
# -----------
161+
162+
for xs in Any["abc", [1, 2, 3]]
163+
@test take(take(xs, 2), 3) === take(xs, 2)
164+
@test take(take(xs, 4), 2) === take(xs, 2)
165+
@test drop(drop(xs, 1), 1) === drop(xs, 2)
166+
@test take(drop(xs, 1), 1) === drop(take(xs, 2), 1)
167+
@test take(drop(xs, 3), 0) === drop(take(xs, 2), 3)
168+
@test isempty(drop(drop(xs, 2), 2))
169+
@test drop(take(drop(xs, 1), 2), 1) === take(drop(xs, 2), 1)
170+
@test take(drop(take(xs, 3), 1), 1) === take(drop(xs, 1), 1)
171+
end
172+
158173
# cycle
159174
# -----
160175

0 commit comments

Comments
 (0)