.net - Why is a dictionary that I define in one module not allowed to be mutated by a second module? -
i define empty mutable dictionary in first module via let mutable. in subsequent module (which aware of first module) try add key-value pair dictionary code never runs (but compile successfully). why?
on other hand, appears dictionary can mutated within module defined in.
code
file1.fs
module file1 let mutable dictionary = system.collections.generic.dictionary<string, int>() file2.fs
module file2 file1.dictionary.add("one",1) program.fs
[<entrypoint>] let main argv = printfn "%a" file1.dictionary.["one"] 0 // return integer exit code error received:
an unhandled exception of type 'system.collections.generic.keynotfoundexception' occurred in mscorlib.dll additional information: given key not present in dictionary.
you don't have calls code in file2. proper way within function, so
file2.fs
module file2 let addone() = file1.dictionary.add("one", 1) program.fs
let main _ = file2.addone() printfn.... that said, global mutable state avoided in f#; it'd more idiomatic have file1.createdict(), , pass file2.addone parameter, not store global variable.
side note don't need mutable marker there, means dictionary reference mutable, not contents (which mutable definition of dictionary).
Comments
Post a Comment