store bug
- Posted by jmduro Mar 09, 2021
- 1083 views
Wen I run following code I get a wrong result:
include std/sequence.e include std/pretty.e include std/console.e sequence s = {"first", {}} sequence t = store(s, {2}, {"second", {}}) pretty_print(1, t, {3}) puts(1, "\n") maybe_any_key()
{ "first", { "first", { "second", "" } } }
So I push back my proposal of April 8th 2018 to replace store and fetch by following code that works:
include std/search.e include std/text.e include std/pretty.e include std/console.e -------------------------------------------------------------------------------- public function get_nested(object structure, sequence targetPath, object def=0, sequence currentPath={}) if equal(currentPath, targetPath) then return structure else integer digit = targetPath[length(currentPath)+1] if digit <= length(structure) then return get_nested(structure[digit], targetPath, def, currentPath&digit) else return def end if end if end function -------------------------------------------------------------------------------- public function set_nested(object structure, sequence targetPath, object x, sequence currentPath={}) integer digit = targetPath[length(currentPath)+1] for i = 1 to digit do if i > length(structure) then structure = append(structure, {}) end if if i = digit then if equal(currentPath&{i}, targetPath) then structure[i] = x else structure[i] = set_nested(structure[i], targetPath, x, currentPath&i) end if end if end for return structure end function -------------------------------------------------------------------------------- public function remove_nested(object structure, sequence targetPath, sequence currentPath={}) integer digit = targetPath[length(currentPath)+1] if digit <= length(structure) then if equal(currentPath&{digit}, targetPath) then structure = remove(structure, digit) else structure[digit] = remove_nested(structure[digit], targetPath, currentPath&digit) end if end if return structure end function ------------------------------------------------------------------------------ sequence s = {"first", {}} sequence t = set_nested(s, {2}, {"second", {}}) pretty_print(1, t, {3}) puts(1, "\n") maybe_any_key()
{ "first", { "second", "" } }
Jean-Marc