Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

make collection constructors more uniform #5897

Merged
merged 5 commits into from
Feb 22, 2014
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
5 changes: 5 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,9 @@ Library improvements
* The `setenv` function for external processes now accepts a `dir` keyword
argument for specifying the directory to start the child process in ([#4888]).

* Constructors for collections (`Set`, `Dict`, etc.) now generally accept a
single iterable argument giving the elements of the collection ([#4996], [#4871])

Deprecated or removed
---------------------

Expand Down Expand Up @@ -270,6 +273,8 @@ Deprecated or removed
[#5748]: https://github.com/JuliaLang/julia/issues/5748
[#5511]: https://github.com/JuliaLang/julia/issues/5511
[#5819]: https://github.com/JuliaLang/julia/issues/5819
[#4871]: https://github.com/JuliaLang/julia/issues/4871
[#4996]: https://github.com/JuliaLang/julia/issues/4996

Julia v0.2.0 Release Notes
==========================
Expand Down
2 changes: 1 addition & 1 deletion base/array.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1328,7 +1328,7 @@ end
# setdiff only accepts two args
function setdiff(a, b)
args_type = promote_type(eltype(a), eltype(b))
bset = Set(b...)
bset = Set(b)
ret = Array(args_type,0)
seen = Set()
for a_elem in a
Expand Down
20 changes: 11 additions & 9 deletions base/collections.jl
Original file line number Diff line number Diff line change
Expand Up @@ -124,13 +124,17 @@ type PriorityQueue{K,V} <: Associative{K,V}

function PriorityQueue(ks::AbstractArray{K}, vs::AbstractArray{V},
o::Ordering)
# TODO: maybe deprecate
if length(ks) != length(vs)
error("key and value arrays must have equal lengths")
end
PriorityQueue{K,V}(zip(ks, vs))
end

xs = Array((K, V), length(ks))
function PriorityQueue(itr, o::Ordering)
xs = Array((K, V), length(itr))
index = Dict{K, Int}()
for (i, (k, v)) in enumerate(zip(ks, vs))
for (i, (k, v)) in enumerate(itr)
xs[i] = (k, v)
if haskey(index, k)
error("PriorityQueue keys must be unique")
Expand All @@ -150,15 +154,13 @@ end

PriorityQueue(o::Ordering=Forward) = PriorityQueue{Any,Any}(o)

function PriorityQueue{K,V}(ks::AbstractArray{K}, vs::AbstractArray{V},
o::Ordering=Forward)
PriorityQueue{K,V}(ks, vs, o)
end
# TODO: maybe deprecate
PriorityQueue{K,V}(ks::AbstractArray{K}, vs::AbstractArray{V},
o::Ordering=Forward) = PriorityQueue{K,V}(ks, vs, o)

function PriorityQueue{K,V}(kvs::Dict{K,V}, o::Ordering=Forward)
PriorityQueue{K,V}([k for k in keys(kvs)], [v for v in values(kvs)], o)
end
PriorityQueue{K,V}(kvs::Associative{K,V}, o::Ordering=Forward) = PriorityQueue{K,V}(kvs, o)

PriorityQueue{K,V}(a::AbstractArray{(K,V)}, o::Ordering=Forward) = PriorityQueue{K,V}(a, o)

length(pq::PriorityQueue) = length(pq.xs)
isempty(pq::PriorityQueue) = isempty(pq.xs)
Expand Down
8 changes: 6 additions & 2 deletions base/deprecated.jl
Original file line number Diff line number Diff line change
Expand Up @@ -395,12 +395,16 @@ eval(Sys, :(@deprecate shlib_list dllist))
@deprecate put put!
@deprecate take take!

@deprecate Set(a, b...) Set({a, b...})
# for a bit of backwards compatibility
IntSet(xs::Integer...) = (s=IntSet(); for a in xs; push!(s,a); end; s)
Set{T<:Number}(xs::T...) = Set{T}(xs)


# 0.3 discontinued functions

function nnz(X)
depwarn("nnz has been renamed to countnz and is no longer computed in constant time for sparse matrices. Instead, use nfilled() for the number of elements in a sparse matrix.", :nnz)
countnz(X)
end
export nnz


9 changes: 9 additions & 0 deletions base/dict.jl
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,14 @@ push!(t::Associative, key, v) = setindex!(t, v, key)
type ObjectIdDict <: Associative{Any,Any}
ht::Array{Any,1}
ObjectIdDict() = new(cell(32))

function ObjectIdDict(itr)
d = ObjectIdDict()
for (k,v) in itr
d[k] = v
end
d
end
end

similar(d::ObjectIdDict) = ObjectIdDict()
Expand Down Expand Up @@ -318,6 +326,7 @@ Dict{K }(ks::(K...), vs::Tuple ) = Dict{K ,Any}(ks, vs)
Dict{V }(ks::Tuple , vs::(V...)) = Dict{Any,V }(ks, vs)

Dict{K,V}(kv::AbstractArray{(K,V)}) = Dict{K,V}(kv)
Dict{K,V}(kv::Associative{K,V}) = Dict{K,V}(kv)

similar{K,V}(d::Dict{K,V}) = (K=>V)[]

Expand Down
6 changes: 3 additions & 3 deletions base/intset.jl
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ type IntSet
IntSet() = new(zeros(Uint32,256>>>5), 256, false)
end

IntSet(args...) = (s=IntSet(); for a in args; push!(s,a); end; s)
IntSet(itr) = (s=IntSet(); for a in itr; push!(s,a); end; s)

similar(s::IntSet) = IntSet()

Expand Down Expand Up @@ -167,7 +167,7 @@ length(s::IntSet) = int(ccall(:bitvector_count, Uint64, (Ptr{Uint32}, Uint64, Ui
(s.fill1s ? typemax(Int) - s.limit : 0)

function show(io::IO, s::IntSet)
print(io, "IntSet(")
print(io, "IntSet([")
first = true
for n in s
if n > s.limit
Expand All @@ -182,7 +182,7 @@ function show(io::IO, s::IntSet)
if s.fill1s
print(io, ", ..., ", typemax(Int)-1, ")")
else
print(io, ")")
print(io, "])")
end
end

Expand Down
2 changes: 1 addition & 1 deletion base/pkg/query.jl
Original file line number Diff line number Diff line change
Expand Up @@ -326,7 +326,7 @@ function dependencies_subset(deps::Dict{ByteString,Dict{VersionNumber,Available}
end

function prune_dependencies(reqs::Requires, deps::Dict{ByteString,Dict{VersionNumber,Available}})
deps = dependencies_subset(deps, Set{ByteString}(keys(reqs)...))
deps = dependencies_subset(deps, Set{ByteString}(keys(reqs)))
deps, _ = prune_versions(reqs, deps)

return deps
Expand Down
2 changes: 1 addition & 1 deletion base/pkg/resolve/interface.jl
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ type Interface
function Interface(reqs::Requires, deps::Dict{ByteString,Dict{VersionNumber,Available}})

# generate pkgs
pkgs = sort!(ByteString[Set{ByteString}(keys(deps)...)...])
pkgs = sort!(ByteString[Set{ByteString}(keys(deps))...])

np = length(pkgs)

Expand Down
10 changes: 6 additions & 4 deletions base/set.jl
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,15 @@ type Set{T}
dict::Dict{T,Nothing}

Set() = new(Dict{T,Nothing}())
Set(x...) = union!(new(Dict{T,Nothing}()), x)
Set(itr) = union!(new(Dict{T,Nothing}()), itr)

# for backwards compat
Set(xs::T...) = Set{T}(xs)
end
Set() = Set{Any}()
Set(x...) = Set{Any}(x...)
Set{T}(x::T...) = Set{T}(x...)
Set(itr) = Set{eltype(itr)}(itr)

show(io::IO, s::Set) = (show(io, typeof(s)); show_comma_array(io, s,'(',')'))
show(io::IO, s::Set) = (show(io, typeof(s)); show_comma_array(io, s,"({","})"))

isempty(s::Set) = isempty(s.dict)
length(s::Set) = length(s.dict)
Expand Down
16 changes: 8 additions & 8 deletions base/show.jl
Original file line number Diff line number Diff line change
Expand Up @@ -212,8 +212,8 @@ print(io::IO, n::Unsigned) = print(io, dec(n))
# original expression.
#
# This is consistent with many other show methods, i.e.:
# show(Set(1,2,3)) # ==> "Set{Int64}(2,3,1)"
# eval(parse("Set{Int64}(2,3,1)”) # ==> An actual set
# show(Set([1,2,3])) # ==> "Set{Int64}([2,3,1])"
# eval(parse("Set{Int64}([2,3,1])”) # ==> An actual set
# While this isn’t true of ALL show methods, it is of all ASTs.

typealias ExprNode Union(Expr, QuoteNode, SymbolNode, LineNumberNode,
Expand All @@ -227,8 +227,8 @@ show_unquoted(io::IO, ex, ::Int,::Int) = show(io, ex)
## AST printing constants ##

const indent_width = 4
const quoted_syms = Set{Symbol}(:(:),:(::),:(:=),:(=),:(==),:(===),:(=>))
const uni_ops = Set{Symbol}(:(+), :(-), :(!), :(~), :(<:), :(>:))
const quoted_syms = Set{Symbol}([:(:),:(::),:(:=),:(=),:(==),:(===),:(=>)])
const uni_ops = Set{Symbol}([:(+), :(-), :(!), :(~), :(<:), :(>:)])
const bin_ops_by_prec = [
"= := += -= *= /= //= .//= .*= ./= \\= .\\= ^= .^= %= .%= |= &= \$= => <<= >>= >>>= ~ .+= .-=",
"?",
Expand All @@ -247,10 +247,10 @@ const bin_ops_by_prec = [
"."
]
const bin_op_precs = Dict{Symbol,Int}(merge([{symbol(op)=>i for op=split(bin_ops_by_prec[i])} for i=1:length(bin_ops_by_prec)]...))
const bin_ops = Set{Symbol}(keys(bin_op_precs)...)
const expr_infix_wide = Set(:(=), :(+=), :(-=), :(*=), :(/=), :(\=), :(&=),
:(|=), :($=), :(>>>=), :(>>=), :(<<=), :(&&), :(||))
const expr_infix = Set(:(:), :(<:), :(->), :(=>), symbol("::"))
const bin_ops = Set{Symbol}(keys(bin_op_precs))
const expr_infix_wide = Set([:(=), :(+=), :(-=), :(*=), :(/=), :(\=), :(&=),
:(|=), :($=), :(>>>=), :(>>=), :(<<=), :(&&), :(||)])
const expr_infix = Set([:(:), :(<:), :(->), :(=>), symbol("::")])
const expr_calls = [:call =>('(',')'), :ref =>('[',']'), :curly =>('{','}')]
const expr_parens = [:tuple=>('(',')'), :vcat=>('[',']'), :cell1d=>('{','}'),
:hcat =>('[',']'), :row =>('[',']')]
Expand Down
9 changes: 5 additions & 4 deletions doc/stdlib/base.rst
Original file line number Diff line number Diff line change
Expand Up @@ -798,13 +798,14 @@ Partially implemented by: ``IntSet``, ``Set``, ``EnvHash``, ``Array``, ``BitArra
Set-Like Collections
--------------------

.. function:: Set(x...)
.. function:: Set([itr])

Construct a ``Set`` with the given elements. Should be used instead of ``IntSet`` for sparse integer sets, or for sets of arbitrary objects.
Construct a ``Set`` of the values generated by the given iterable object, or an empty set.
Should be used instead of ``IntSet`` for sparse integer sets, or for sets of arbitrary objects.

.. function:: IntSet(i...)
.. function:: IntSet([itr])

Construct a sorted set of the given integers. Implemented as a bit string, and therefore designed for dense integer sets. If the set will be sparse (for example holding a single very large integer), use ``Set`` instead.
Construct a sorted set of the integers generated by the given iterable object, or an empty set. Implemented as a bit string, and therefore designed for dense integer sets. If the set will be sparse (for example holding a single very large integer), use ``Set`` instead.

.. function:: union(s1,s2...)

Expand Down
52 changes: 26 additions & 26 deletions test/collections.jl
Original file line number Diff line number Diff line change
Expand Up @@ -198,24 +198,24 @@ end

# isempty
@test isempty(Set())
@test !isempty(Set(1))
@test !isempty(Set("banana", "apple"))
@test !isempty(Set(1, 1:10, "pear"))
@test !isempty(Set([1]))
@test !isempty(Set(["banana", "apple"]))
@test !isempty(Set({1, 1:10, "pear"}))

# ordering
@test Set() < Set(1)
@test Set(1) < Set(1,2)
@test !(Set(3) < Set(1,2))
@test !(Set(3) > Set(1,2))
@test Set(1,2,3) > Set(1,2)
@test !(Set(3) <= Set(1,2))
@test !(Set(3) >= Set(1,2))
@test Set(1) <= Set(1,2)
@test Set(1,2) <= Set(1,2)
@test Set(1,2) >= Set(1,2)
@test Set(1,2,3) >= Set(1,2)
@test !(Set(1,2,3) >= Set(1,2,4))
@test !(Set(1,2,3) <= Set(1,2,4))
@test Set() < Set([1])
@test Set([1]) < Set([1,2])
@test !(Set([3]) < Set([1,2]))
@test !(Set([3]) > Set([1,2]))
@test Set([1,2,3]) > Set([1,2])
@test !(Set([3]) <= Set([1,2]))
@test !(Set([3]) >= Set([1,2]))
@test Set([1]) <= Set([1,2])
@test Set([1,2]) <= Set([1,2])
@test Set([1,2]) >= Set([1,2])
@test Set([1,2,3]) >= Set([1,2])
@test !(Set([1,2,3]) >= Set([1,2,4]))
@test !(Set([1,2,3]) <= Set([1,2,4]))

# add, length
s = Set()
Expand All @@ -236,7 +236,7 @@ end

# elements
data_in = (1,"banana", ())
s = Set(data_in...)
s = Set(data_in)
data_out = collect(s)
@test is(typeof(data_out), Array{Any,1})
@test all(map(d->in(d,data_out), data_in))
Expand All @@ -246,15 +246,15 @@ data_out = collect(s)
@test length(data_out) == length(data_in)

# homogeneous sets
@test is(typeof(Set(1,2,3)), Set{Int})
@test is(typeof(Set{Int}(3)), Set{Int})
@test is(typeof(Set([1,2,3])), Set{Int})
@test is(typeof(Set{Int}([3])), Set{Int})

# eltype
@test is(eltype(Set(1,"hello")), Any)
@test is(eltype(Set({1,"hello"})), Any)
@test is(eltype(Set{String}()), String)

# no duplicates
s = Set(1,2,3)
s = Set([1,2,3])
@test length(s) == 3
push!(s,2)
@test length(s) == 3
Expand Down Expand Up @@ -332,16 +332,16 @@ setdiff!(s,(3,5))
@test isequal(s,Set(1,7))

# similar
s = similar(Set(1,"Banana"))
s = similar(Set([1,"Banana"]))
@test length(s) == 0
@test typeof(s) == Set{Any}
s = similar(Set{Float32}(2.0f0,3.0f0,4.0f0))
s = similar(Set{Float32}([2.0f0,3.0f0,4.0f0]))
@test length(s) == 0
@test typeof(s) == Set{Float32}

# copy
data_in = (1,2,9,8,4)
s = Set(data_in...)
s = Set(data_in)
c = copy(s)
@test isequal(s,c)
push!(s,100)
Expand All @@ -352,7 +352,7 @@ push!(c,200)
# start, done, next
for data_in in ((7,8,4,5),
("hello", 23, 2.7, (), [], (1,8)))
s = Set(data_in...)
s = Set(data_in)

s_new = Set()
for el in s
Expand All @@ -379,7 +379,7 @@ end
end

# pop!
origs = Set(1,2,3,"apple")
origs = Set([1,2,3,"apple"])
s = copy(origs)
for i in 1:length(origs)
el = pop!(s)
Expand Down
2 changes: 1 addition & 1 deletion test/perf/kernel/actor_centrality.jl
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ end

function centrality_mean(G::Graph, start_node)
dists = Dict{Node,Uint64}()
next = Set(G[start_node])
next = Set([G[start_node]])

cdist = 0
while !isempty(next)
Expand Down
4 changes: 2 additions & 2 deletions test/perf/spell/perf.jl
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ function edits1(word::String)
transposes = ["$a$(b[2])$(b[1])$(b[3:end])" for (a,b) in splits[1:end-2]]
replaces = ["$a$c$(b[2:end])" for (a,b) in splits[1:end-1], c in alphabet]
inserts = ["$a$c$b" for (a,b) in splits, c in alphabet]
return Set(deletes..., transposes..., replaces..., inserts...)
return Set([deletes; transposes; replaces[:]; inserts[:]])
end

function known_edits2(word::String)
Expand All @@ -63,7 +63,7 @@ function correct(word::String)
candidates = known([word])
length(candidates) == 0 && (candidates = known(edits1(word)))
length(candidates) == 0 && (candidates = known_edits2(word) )
length(candidates) == 0 && (candidates = Set(word) )
length(candidates) == 0 && (candidates = Set([word]) )

maximum(x->(get(NWORDS, x, 0),x), candidates)[2]
end
Expand Down