Iterate over an array in a function

For my Google Spreadsheet module , I would like the function to be able to take an array of values ​​and iterate over them, adding them to the hash. A spreadsheet presentation form requires values ​​in this format:

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

If the function takes an array like the following,

 [value0, value1, value2] 

Is it possible to loop over them, save the work counter and create a hash? This would be a simple task in other languages. Python is enough to illustrate:

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

Can this be done in KRL?

+6
krl
source share
1 answer

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 {'entry.1.single' :'value1','entry.0.single' :'value0','entry.2.single' :'value2'};

A recursive function is needed here because you are performing a structure transformation. If you want to return an array, you could use the map() method.

Also note that your base register writes recursive functions. KNS sets a recursion limit.

+3
source share

All Articles