Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating over an array in a function

Tags:

krl

For my Google Docs spreadsheet module, I'd like a function to be able to accept an array of values and iterate over them, adding them to a hash. The spreadsheet submission form wants values in a format like this:

{"entry.0.single": value0,
 "entry.1.single": value1,
 "entry.2.single": value2}

If the function accepts an array like the following,

[value0, value1, value2]

is it possible to loop over them, keep a running counter, and create a hash? This would be a simple task in other languages. Python suffices for illustration:

hash = dict()
i = 0
for val in values:
  hash["entry.%s.single" % i] = val
  i += 1

Can that be done in KRL?

like image 244
Steve Nay Avatar asked Apr 05 '11 04:04

Steve Nay


1 Answers

Recursive functions are your friend:

    a = ['value0', 'value1', 'value2'];

    r = function(a, h, n){
      top = a.head();
      newhash = h.put({'entry.#{n}.single':top});
      a.length() > 1 => r(a.tail(), newhash, n+1) | newhash;
    };

    out = r(a, {}, 0);

out has the value of {'entry.1.single' :'value1','entry.0.single' :'value0','entry.2.single' :'value2'};

A recursive function is needed here because you are doing a structure conversion. If you wanted an array back, you could have used the map() method.

Also, watch your base case writing recursive functions. KNS does enforce a recursion limit.

like image 188
TelegramSam Avatar answered Oct 23 '22 23:10

TelegramSam