fetch & store
- Posted by jmduro Mar 30, 2018
- 1425 views
Here is a proposal for the replacement of fetch and store.
- get_object returns a default value when object is not found in sequence instead of providing an error message.
- set_object simply doesn't the job if the path to storage location cannot be followed to its end instead of providing an error message.
include std/search.e include std/types.e ------------------------------------------------------------------------------ function get_object(object structure, sequence target, object default=0, sequence path={}) if atom(structure) then if equal(path, target) then return structure end if else if t_text(structure) then if equal(path, target) then return structure end if else for i=1 to length(structure) do if sequence(structure[i]) then object o = get_object(structure[i], target, default, path&i) if not equal(o, default) then return o end if else if equal(path, target) then return structure end if end if end for end if end if return default end function ------------------------------------------------------------------------------ function set_object(object structure, sequence target, object x, sequence path={}) if atom(structure) then if equal(path, target) then structure = x end if else if t_text(structure) then if equal(path, target) then structure = x end if else for i=1 to length(structure) do if sequence(structure[i]) then if begins(path, target) then structure[i] = set_object(structure[i], target, x, path&i) end if else if equal(path, target) then structure[i] = x end if end if end for end if end if return structure end function
Here is an example of usage:
include std/pretty.e include std/console.e sequence structure = {{{"admin", {"software"}}}, {{"configure", {"access-control"}}}} pretty_print(1, structure, {3}) puts(1, "\n") printf(1, "get_object(structure, {1,1,2,1}) = %s\n", {get_object(structure, {1,1,2,1})}) structure = set_object(structure, {1,1,2,1}, "new") pretty_print(1, structure, {3}) puts(1, "\n") printf(1, "get_object(structure, {1,1,2,1}) = %s\n", {get_object(structure, {1,1,2,1})}) structure = set_object(structure, {1,3}, "added") -- path not found, no crash pretty_print(1, structure, {3}) puts(1, "\n") maybe_any_key()
Jean-Marc