julia lang - Immutable dictionary -
is there way enforce dictionary being constant?
i have function reads out file parameters (and ignores comments) , stores in dict:
function getparameters(filename::abstractstring) f = open(filename,"r") dict = dict{abstractstring, abstractstring}() ln in eachline(f) m = match(r"^\s*(?p<key>\w+)\s+(?p<value>[\w+-.]+)", ln) if m != nothing dict[m[:key]] = m[:value] end end close(f) return dict end
this works fine. since have lot of parameters, end using on different places, idea let dict global. , know, global variables not great, wanted ensure dict , members immutable.
is approach? how do it? have it?
bonus answerable stuff :)
is code ok? (it first thing did julia, , coming c/c++ , python have tendencies things differently.) need check whether file open? reading of file "julia"-like? readall
, use eachmatch
. don't see "right way it" (like in python).
why not use immutabledict? it's defined in base not exported. use 1 follows:
julia> id = base.immutabledict("key1"=>1) base.immutabledict{string,int64} 1 entry: "key1" => 1 julia> id["key1"] 1 julia> id["key1"] = 2 error: methoderror: no method matching setindex!(::base.immutabledict{string,int64}, ::int64, ::string) in eval(::module, ::any) @ .\boot.jl:234 in macro expansion @ .\repl.jl:92 [inlined] in (::base.repl.##1#2{base.repl.replbackend})() @ .\event.jl:46 julia> id2 = base.immutabledict(id,"key2"=>2) base.immutabledict{string,int64} 2 entries: "key2" => 2 "key1" => 1 julia> id.value 1
you may want define constructor takes in array of pairs (or keys , values) , uses algorithm define whole dict (that's way so, see note @ bottom).
just added note, actual internal representation each dictionary contains 1 key-value pair, , dictionary. method walks through dictionaries checking if has right value. reason because arrays mutable: if did naive construction of immutable type mutable field, field still mutable , while id["key1"]=2
wouldn't work, id.keys[1]=2
would. go around not using mutable type holding values (thus holding single values) , holding immutable dict. if wanted make work directly on arrays, use immutablearrays.jl don't think you'd performance advantage because you'd still have loop through array when checking key...
Comments
Post a Comment