1. Re: Constructing an array value from a sequence -Another way

Jiri's code starts with the full data-set as the new first sequence, then
adds sequences to it.
 It can produce an interim memory object considerably bigger than the
original data-set.

The method below builds the new data starting from a zero-length sequence,
and grows to full
size, kind of like un-peeling an onion.

This also includes an optional error checking routine,
  which will avoid attempts to write out-of-bounds and
  prevent inserting a sequence inside a sequence which contains only atoms
  (like trying to put "hand" into "glove" -> {gl{hand}ve}


doug edmunds


 ----------------snip here------------------
function error_check(sequence data, sequence loc)
  sequence error
  error = {0,"none"}
  for x = 1 to length(loc) do
    if length(data) < loc[x] then
      error[1] = 1
      error[2] = sprintf("%s %d",{"Out of bounds: element",x})
      exit
    end if
    if not sequence(data[loc[x]]) then
      error[1] = 2
      error[2] = sprintf("%s %d",{"Atom, not sequence: element",x})
      exit
    else
      data = data[loc[x]]  --go to next level
    end if
  end for
return error
end function

function read_data(sequence data, sequence loc)
  integer  len
  len = length(loc)
  for x = 1 to len do
    data = data[loc[x]]  --go to next level
  end for
  return data
end function

function write_data(sequence data, sequence loc, sequence new_value)
  sequence new_data
  integer len
  len = length(loc)
  new_data = {}
  for x = len to 1 by -1 do
    new_data = read_data(data, loc[1..x-1])
    new_data[loc[x]] = new_value
    new_value = new_data
  end for
  return new_data
end function

---------------  testing routines  --------------------

object data
sequence loc, new_value, err_check


data = {{"a",{"aa", "ab","ac"}},"bbb","ccc"}
new_value = "xxxxxxx"
loc = {1,2,1}
--try changing loc to an invalid sequence, like {3,99} , to see how error
checking works


printf(1,"Sequence: ",{})
? loc
puts(1,"New value: ")
? new_value
puts(1,"before\n")
? data
err_check = error_check(data, loc)
if err_check[1]= 0 then -- no error, write the change
  data = write_data(data, loc, new_value)
  puts(1,"\n")
puts(1,"after\n")
? data
else
  printf(1,"Error %d - %s; changes not written\n",{err_check[1],
err_check[2]})
end if
puts(1,"\n")

------------- end code ----------------

new topic     » topic index » view message » categorize

Search



Quick Links

User menu

Not signed in.

Misc Menu