Skip to content
Merged
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
13 changes: 12 additions & 1 deletion src/Utilities/lazy_iterators.jl
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
struct EmptyVector{T} <: AbstractVector{T} end

Base.size(::EmptyVector) = (0,)

Base.isempty(::EmptyVector) = true

Base.eltype(::EmptyVector{T}) where {T} = T

Base.iterate(::EmptyVector) = nothing

"""
Expand All @@ -18,21 +22,28 @@ struct LazyMap{T,VT,F}
f::F
data::VT
end

function LazyMap{T}(f, data) where {T}
return LazyMap{T,typeof(data),typeof(f)}(f, data)
end

Base.size(it::LazyMap) = size(it.data)

Base.length(it::LazyMap) = length(it.data)

function Base.iterate(it::LazyMap, args...)
elem_state = iterate(it.data, args...)
if elem_state === nothing
return nothing
return
else
return it.f(elem_state[1]), elem_state[2]
end
end

Base.IteratorSize(it::LazyMap) = Base.IteratorSize(it.data)

Base.eltype(::LazyMap{T}) where {T} = T

function Iterators.reverse(it::LazyMap{T}) where {T}
return LazyMap{T}(it.f, Iterators.reverse(it.data))
end
37 changes: 31 additions & 6 deletions test/Utilities/lazy_iterators.jl
Original file line number Diff line number Diff line change
@@ -1,10 +1,23 @@
using Test
module TestLazyIterators

using MathOptInterface
using Test

const MOI = MathOptInterface
const MOIU = MOI.Utilities

@testset "EmptyVector{$T}" for T in [Int, Float64]
v = MOIU.EmptyVector{T}()
function runtests()
for name in names(@__MODULE__; all = true)
if startswith("$(name)", "test_")
@testset "$(name)" begin
getfield(@__MODULE__, name)()
end
end
end
return
end

function _test_EmptyVector(T)
v = MOI.Utilities.EmptyVector{T}()
@test size(v) == (0,)
@test length(v) == 0
@test isempty(v)
Expand All @@ -13,15 +26,27 @@ const MOIU = MOI.Utilities
c = collect(v)
@test c isa Vector{T}
@test isempty(c)
return
end

@testset "LazyMap{$T}" for T in [Int, Float64]
v = MOIU.LazyMap{T}(x -> x^2, [2, 3])
test_EmptyVector_Int() = _test_EmptyVector(Int)
test_EmptyVector_Float64() = _test_EmptyVector(Float64)

function _test_LazyMap(T)
v = MOI.Utilities.LazyMap{T}(x -> x^2, [2, 3])
@test size(v) == (2,)
@test length(v) == 2
@test !isempty(v)
@test eltype(v) == T
c = collect(v)
@test c isa Vector{T}
@test c == [4, 9]
return
end

test_LazyMap_Int() = _test_LazyMap(Int)
test_LazyMap_Float64() = _test_LazyMap(Float64)

end # module

TestLazyIterators.runtests()