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

Add Dict comprehensions and typed Dicts -- alternative version (changes Dict literal notation) #1478

Merged
merged 5 commits into from
Nov 1, 2012
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
15 changes: 10 additions & 5 deletions base/dict.jl
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,16 @@ const _jl_secret_table_token = :__c782dbf1cf4d6a2e5e3865d7e95634f2e09b5902__
has(t::Associative, key) = !is(get(t, key, _jl_secret_table_token),
_jl_secret_table_token)

function show(io, t::Associative)
function show{K,V}(io, t::Associative{K,V})
if isempty(t)
print(io, typeof(t),"()")
else
print(io, "{")
if K === Any && V === Any
delims = ['{','}']
else
delims = ['[',']']
end
print(io, delims[1])
first = true
for (k, v) = t
first || print(io, ',')
Expand All @@ -20,7 +25,7 @@ function show(io, t::Associative)
print(io, "=>")
show(io, v)
end
print(io, "}")
print(io, delims[2])
end
end

Expand Down Expand Up @@ -252,7 +257,7 @@ Dict{K,V}(ks::(K...), vs::(V...)) = Dict{K ,V }(ks, vs)
Dict{K }(ks::(K...), vs::Tuple ) = Dict{K ,Any}(ks, vs)
Dict{V }(ks::Tuple , vs::(V...)) = Dict{Any,V }(ks, vs)

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

function serialize(s, t::Dict)
serialize_type(s, typeof(t))
Expand Down Expand Up @@ -463,7 +468,7 @@ end
type WeakKeyDict{K,V} <: Associative{K,V}
ht::Dict{Any,V}

WeakKeyDict() = new(Dict{Any,V}())
WeakKeyDict() = new((Any=>V)[])
end
WeakKeyDict() = WeakKeyDict{Any,Any}()

Expand Down
2 changes: 1 addition & 1 deletion base/intfuncs.jl
Original file line number Diff line number Diff line change
Expand Up @@ -407,7 +407,7 @@ function factor{T<:Integer}(n::T)
if n <= 0
error("factor: number to be factored must be positive")
end
h = Dict{T,Int}()
h = (T=>Int)[]
if n == 1 return h end
local p::T
s = ifloor(sqrt(n))
Expand Down
2 changes: 1 addition & 1 deletion base/pkg.jl
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ end

function _resolve()
reqs = parse_requires("REQUIRE")
have = Dict{String,ASCIIString}()
have = (String=>ASCIIString)[]
Git.each_submodule(false) do pkg, path, sha1
if pkg != "METADATA"
have[pkg] = sha1
Expand Down
2 changes: 1 addition & 1 deletion base/pkgmetadata.jl
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ function resolve(reqs::Vector{VersionSet})
zeros(Int,length(deps)) ]

x = Main.linprog_simplex(w,[V;R;D],b,nothing,nothing,z,u)[2]
h = Dict{String,ASCIIString}()
h = (String=>ASCIIString)[]
for v in vers[x .> 0.5]
h[v.package] = readchomp("METADATA/$(v.package)/versions/$(v.version)/sha1")
end
Expand Down
4 changes: 2 additions & 2 deletions base/process.jl
Original file line number Diff line number Diff line change
Expand Up @@ -208,8 +208,8 @@ type Cmd
end
this = new(exec,
"",
Dict{FileDes,PipeEnd}(),
Dict{FileDes,FileSink}(),
(FileDes=>PipeEnd)[],
(FileDes=>FileSink)[],
FileDes[],
Set{Cmd}(),
0,
Expand Down
2 changes: 1 addition & 1 deletion base/set.jl
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
type Set{T}
hash::Dict{T,Bool}

Set() = new(Dict{T,Bool}())
Set() = new((T=>Bool)[])
Set(x...) = add_each(new(Dict{T,Bool}(length(x))), x)
end
Set() = Set{Any}()
Expand Down
4 changes: 2 additions & 2 deletions base/show.jl
Original file line number Diff line number Diff line change
Expand Up @@ -192,8 +192,8 @@ show_unquoted(io::IO, x::String, indent::Int) = show(io, x)
const _expr_infix_wide = Set(:(=), :(+=), :(-=), :(*=), :(/=), :(\=), :(&=),
:(|=), :($=), :(>>>=), :(>>=), :(<<=), :(&&), :(||))
const _expr_infix = Set(:(:), :(<:), :(->), :(=>), symbol("::"))
const _expr_calls = {:call =>('(',')'), :ref =>('[',']'), :curly =>('{','}')}
const _expr_parens = {:tuple=>('(',')'), :vcat=>('[',']'), :cell1d=>('{','}')}
const _expr_calls = [:call =>('(',')'), :ref =>('[',']'), :curly =>('{','}')]
const _expr_parens = [:tuple=>('(',')'), :vcat=>('[',']'), :cell1d=>('{','}')]

function show_unquoted(io::IO, ex::Expr, indent::Int)
head, args, nargs = ex.head, ex.args, length(ex.args)
Expand Down
2 changes: 1 addition & 1 deletion base/util.jl
Original file line number Diff line number Diff line change
Expand Up @@ -165,7 +165,7 @@ methods(t::CompositeKind) = (methods(t,Tuple); # force constructor creation

# require
# Store list of files and their load time
global _jl_package_list = Dict{ByteString,Float64}()
global _jl_package_list = (ByteString=>Float64)[]
require(fname::String) = require(bytestring(fname))
require(f::String, fs::String...) = (require(f); for x in fs require(x); end)
function require(name::ByteString)
Expand Down
6 changes: 3 additions & 3 deletions extras/argparse.jl
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ _cmd_dest_name = "%COMMAND%"
type ArgParseTable
fields::Vector{ArgParseField}
subsettings::Dict{String,Any} # this in fact will be a Dict{String,ArgParseSettings}
ArgParseTable() = new(ArgParseField[], Dict{String,Any}())
ArgParseTable() = new(ArgParseField[], (String=>Any)[])
end
#}}}

Expand Down Expand Up @@ -1495,7 +1495,7 @@ function _show_help(settings::ArgParseSettings)

usage_str = usage_string(settings)

group_lists = Dict{String,Vector{Any}}()
group_lists = (String=>Vector{Any})[]
for ag in settings.args_groups
group_lists[ag.name] = Any[]
end
Expand Down Expand Up @@ -1626,7 +1626,7 @@ function _parse_args_unhandled(args_list::Vector, settings::ArgParseSettings)
end

found_args = Set{String}()
out_dict = Dict{String,Any}()
out_dict = (String=>Any)[]

for f in settings.args_table.fields
if f.action == :show_help || f.action == :show_version
Expand Down
34 changes: 17 additions & 17 deletions extras/cairo.jl
Original file line number Diff line number Diff line change
Expand Up @@ -394,21 +394,21 @@ function _set_color( ctx::CairoContext, color )
end

function _set_line_type(ctx::CairoContext, nick::String)
const nick2name = {
const nick2name = [
"dot" => "dotted",
"dash" => "shortdashed",
"dashed" => "shortdashed",
}
]
# XXX:should be scaled by linewidth
const name2dashes = {
const name2dashes = [
"solid" => Float64[],
"dotted" => [1.,3.],
"dotdashed" => [1.,3.,4.,4.],
"longdashed" => [6.,6.],
"shortdashed" => [4.,4.],
"dotdotdashed" => [1.,3.,1.,3.,4.,4.],
"dotdotdotdashed" => [1.,3.,1.,3.,1.,3.,4.,4.],
}
]
name = get(nick2name, nick, nick)
if has(name2dashes, name)
set_dash(ctx, name2dashes[name])
Expand Down Expand Up @@ -451,7 +451,7 @@ function _str_size_to_pts( str )
num_xx = float64(m.captures[1])
units = m.captures[2]
# convert to postscipt pt = in/72
const xx2pt = { "in"=>72., "pt"=>1., "mm"=>2.835, "cm"=>28.35 }
const xx2pt = [ "in"=>72., "pt"=>1., "mm"=>2.835, "cm"=>28.35 ]
num_pt = num_xx*xx2pt[units]
return num_pt
end
Expand Down Expand Up @@ -497,7 +497,7 @@ end

## state commands

const __pl_style_func = {
const __pl_style_func = [
"color" => _set_color,
"linecolor" => _set_color,
"fillcolor" => _set_color,
Expand All @@ -506,7 +506,7 @@ const __pl_style_func = {
"linewidth" => set_line_width,
"filltype" => set_fill_type,
"cliprect" => set_clip_rect,
}
]

function set( self::CairoRenderer, key::String, value )
set(self.state, key, value )
Expand Down Expand Up @@ -589,7 +589,7 @@ function symbols( self::CairoRenderer, x, y )
name = pop(splitname)
filled = contains(splitname, "solid") || contains(splitname, "filled")

const symbol_funcs = {
const symbol_funcs = [
"asterisk" => (c, x, y, r) -> (
_move_to(c, x, y+r);
_line_to(c, x, y-r);
Expand Down Expand Up @@ -649,7 +649,7 @@ function symbols( self::CairoRenderer, x, y )
_line_to(c, x+0.5r, y-0.866r);
close_path(c)
),
}
]
default_symbol_func = (ctx,x,y,r) -> (
new_sub_path(ctx);
_circle(ctx,x,y,r)
Expand Down Expand Up @@ -723,13 +723,13 @@ function text( self::CairoRenderer, p, text )
layout_text(self, text)
update_layout(self.ctx)

const _xxx = {
const _xxx = [
"center" => 0.5,
"left" => 0.,
"right" => 1.,
"top" => 0.,
"bottom" => 1.,
}
]
extents = get_layout_size(self.ctx)
dx = -_xxx[halign]*extents[1]
dy = _xxx[valign]*extents[2]
Expand Down Expand Up @@ -803,7 +803,7 @@ function peek( self::TeXLexer )
return token
end

const _common_token_dict = {
const _common_token_dict = [
L"\{" => L"{",
L"\}" => L"}",
L"\_" => L"_",
Expand All @@ -813,17 +813,17 @@ const _common_token_dict = {
## ignore stray brackets
L"{" => L"",
L"}" => L"",
}
]

const _text_token_dict = {
const _text_token_dict = [
## non-math symbols (p438)
L"\S" => E"\ua7",
L"\P" => E"\ub6",
L"\dag" => E"\u2020",
L"\ddag" => E"\u2021",
}
]

const _math_token_dict = {
const _math_token_dict = [

L"-" => E"\u2212", # minus sign

Expand Down Expand Up @@ -1074,7 +1074,7 @@ const _math_token_dict = {
L"\arcdeg" => E"\ub0",
L"\arcmin" => E"\u2032",
L"\arcsec" => E"\u2033",
}
]

function map_text_token(token::String)
if has(_text_token_dict, token)
Expand Down
4 changes: 2 additions & 2 deletions extras/color.jl
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ function name2rgb( name::String )
(ir/255., ig/255., ib/255.)
end

const _jl_color_names = {
const _jl_color_names = [
"y" => (255, 255, 0),
"m" => (255, 0, 255),
"c" => (0, 255, 255),
Expand Down Expand Up @@ -213,7 +213,7 @@ const _jl_color_names = {
"whitesmoke" => (245, 245, 245),
"yellow" => (255, 255, 0),
"yellowgreen" => (154, 205, 50),
}
]

## Color spaces
abstract ColorSpace
Expand Down
2 changes: 1 addition & 1 deletion extras/inifile.jl
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ type IniFile
defaults::HTSS
end

IniFile() = IniFile(Dict{String,HTSS}(), HTSS())
IniFile() = IniFile((String=>HTSS)[], HTSS())

function read(inifile::IniFile, stream::IOStream)
current_section = inifile.defaults
Expand Down
2 changes: 1 addition & 1 deletion extras/json.jl
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ function parse_json(strng::String)

function parse_object()
parse_char('{')
object = Dict{String, Any}()
object = (String=>Any)[]
if next_char() != '}'
while true
str = parse_string()
Expand Down
2 changes: 1 addition & 1 deletion extras/memoize.jl
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ macro memoize(ex)
f_cache = esc(symbol(string(f,"_cache")))
quote
$(esc(ex))
const ($f_cache) = Dict{Tuple,Any}()
const ($f_cache) = (Tuple=>Any)[]
$(esc(f))(args...) = has(($f_cache),args) ?
($f_cache)[args] : (($f_cache)[args] = $(esc(u))(args...))
end
Expand Down
2 changes: 1 addition & 1 deletion extras/options.jl
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ end
# Constructor: supply type followed by list of assignment expressions, e.g.,
# o = Options(CheckNone,:(a=5),:(b=rand(3)),...)
function Options{T<:OptionsChecking}(::Type{T},ex::Expr...)
ht = Dict{Symbol,Int}()
ht = (Symbol=>Int)[]
vals = Array(Any,0)
n = length(ex)
for i = 1:n
Expand Down
8 changes: 4 additions & 4 deletions extras/plot.jl
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ function loglog(args...)
_plot(p, args...)
end

const chartokens = {
const chartokens = [
'-' => {"linestyle" => "solid"},
':' => {"linestyle" => "dotted"},
';' => {"linestyle" => "dotdashed"},
Expand All @@ -58,12 +58,12 @@ const chartokens = {
'b' => {"color" => "blue"},
'w' => {"color" => "white"},
'k' => {"color" => "black"},
}
]

function _parse_style(spec::String)
style = Dict()

for (k,v) in { "--" => "dashed", "-." => "dotdashed" }
for (k,v) in [ "--" => "dashed", "-." => "dotdashed" ]
splitspec = split(spec, k)
if length(splitspec) > 1
style["linestyle"] = v
Expand Down Expand Up @@ -106,7 +106,7 @@ function _plot(p::FramedPlot, args...)
# TODO
else
y = shift(args)
style = { "linestyle" => "solid" } # TODO:cycle colors
style = [ "linestyle" => "solid" ] # TODO:cycle colors
if length(args) > 0 && typeof(args[1]) <: String
style = _parse_style(shift(args))
end
Expand Down
Loading