1
struct EnumerableTake{T,S} <: Enumerable
2 23
    source::S
3
    n::Int
4
end
5

6
function take(source::Enumerable, n::Integer)
7 23
    T = eltype(source)
8
    S = typeof(source)
9 23
    return EnumerableTake{T,S}(source, Int(n))
10
end
11

12 0
Base.IteratorSize(::Type{EnumerableTake{T,S}}) where {T,S} = haslength(S)
13

14 0
Base.eltype(::Type{EnumerableTake{T,S}}) where {T,S} = T
15

16 5
Base.length(iter::EnumerableTake{T,S}) where {T,S} = min(length(iter.source),iter.n)
17

18
function Base.iterate(iter::EnumerableTake{T,S}) where {T,S}
19 23
    ret = iterate(iter.source)
20

21 23
    if ret===nothing
22 0
        return nothing
23 23
    elseif iter.n==0
24 0
        return nothing
25
    else
26 23
        return ret[1], (ret[2],1)
27
    end
28
end
29

30
function Base.iterate(iter::EnumerableTake{T,S}, state) where {T,S}
31 23
    if state[2]==iter.n
32 23
        return nothing
33
    else
34 18
        ret = iterate(iter.source, state[1])
35

36 23
        if ret===nothing
37 0
            return nothing
38
        else
39 23
            return ret[1], (ret[2], state[2]+1)
40
        end
41
    end
42
end

Read our documentation on viewing source code .

Loading