Skip to content

Commit

Permalink
Move SingletonVector and SingletonDict to a different file
Browse files Browse the repository at this point in the history
  • Loading branch information
tkf committed Jun 30, 2019
1 parent ead1401 commit e7e6b1f
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 26 deletions.
1 change: 1 addition & 0 deletions src/NoBang/NoBang.jl
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ using Base: ImmutableDict
using Requires
using Setfield: setproperties

include("singletoncontainers.jl")
include("base.jl")
include("linearalgebra.jl")

Expand Down
26 changes: 0 additions & 26 deletions src/NoBang/base.jl
Original file line number Diff line number Diff line change
Expand Up @@ -7,34 +7,8 @@ const ImmutableContainer = Union{
push(xs, i1, i2, items...) =
foldl(push, items, init=push(push(xs, i1), i2))

# A helper type for implementing `push`
struct SingletonVector{T} <: AbstractVector{T}
value::T
end

Base.size(::SingletonVector) = (1,)

function Base.getindex(v::SingletonVector, i::Integer)
@boundscheck i == 1 || throw(BoundsError(v, i))
return v.value
end

push(xs::AbstractVector, x) = vcat(xs, SingletonVector(x))
push(xs::AbstractSet, x) = union(xs, SingletonVector(x))

struct SingletonDict{K, V} <: AbstractDict{K, V}
key::K
value::V
end

Base.iterate(d::SingletonDict) = (d.key => d.value, nothing)
Base.iterate(d::SingletonDict, ::Nothing) = nothing

function Base.getindex(d::SingletonDict{K}, key::K) where K
@boundscheck d.key == key || throw(BoundsError(d, key))
return d.value
end

push(xs::AbstractDict, x::Pair) = merge(xs, SingletonDict(x[1], x[2]))

push(xs::Tuple, items...) = (xs..., items...)
Expand Down
27 changes: 27 additions & 0 deletions src/NoBang/singletoncontainers.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
# Helper types for implementing `push`


struct SingletonVector{T} <: AbstractVector{T}
value::T
end

Base.size(::SingletonVector) = (1,)

function Base.getindex(v::SingletonVector, i::Integer)
@boundscheck i == 1 || throw(BoundsError(v, i))
return v.value
end


struct SingletonDict{K, V} <: AbstractDict{K, V}
key::K
value::V
end

Base.iterate(d::SingletonDict) = (d.key => d.value, nothing)
Base.iterate(d::SingletonDict, ::Nothing) = nothing

function Base.getindex(d::SingletonDict{K}, key::K) where K
@boundscheck d.key == key || throw(BoundsError(d, key))
return d.value
end

0 comments on commit e7e6b1f

Please sign in to comment.