Skip to content

Instantly share code, notes, and snippets.

@HarlanH
Created August 17, 2012 21:47
Show Gist options
  • Save HarlanH/3382989 to your computer and use it in GitHub Desktop.
Save HarlanH/3382989 to your computer and use it in GitHub Desktop.
IndexDict.jl
type IndexDict{V} <: Associative{ByteString,V}
idx::Index
arr::Vector{V}
IndexDict() = new(Index(), Array(V,0))
end
IndexDict() = IndexDict{Any}()
# assignment by a string replaces or appends
function assign(id::IndexDict, v, key::ByteString)
if has(id.idx, key)
id.arr[id.idx[key]] = v
else
push(id.arr, v)
push(id.idx, key)
end
end
# assignment by an integer replaces or throws an error
assign(id::IndexDict, v, pos) = id.arr[pos] = v
ref(id::IndexDict, i) = id.arr[id.idx[i]]
function get{K}(id::IndexDict{K}, key, deflt)
try
id[key]
catch e
deflt
end
end
has(id::IndexDict, key) = has(id.idx, key)
isempty(id::IndexDict) = isempty(id.arr)
length(id::IndexDict) = length(id.arr)
start(id::IndexDict) = 1
done(id::IndexDict, i) = i > length(id)
next(id::IndexDict, i) = (id[i], i+1)
function show(io, id::IndexDict)
n = names(id.idx)
for i = 1:min(length(id), 9)
println(io, "$i, $(n[i]): $(id[i])")
end
if length(id) > 9
println(io, "...")
end
end
julia> nams = ["one", "two", "three", "four"]
4-element ASCIIString Array:
"one"
"two"
"three"
"four"
julia> vals = [11, 22, 33, 44]
4-element Int64 Array:
11
22
33
44
julia> t1 = IndexDict()
julia> for i = 1:4
t1[nams[i]] = vals[i]
end
julia> print(t1)
1, one: 11
2, two: 22
3, three: 33
4, four: 44
julia> t1["one"]
11
julia> t1[1]
11
julia> t1["two"]
22
julia> t1[2]
22
julia> t1[1:2]
2-element Any Array:
11
22
julia> t1[["one", "three"]]
2-element Any Array:
11
33
julia> [x for x in t1]
4-element Any Array:
11
22
33
44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment