Applying an operation on each element of nested list

  • A+
Category:Languages

I have a complex nested list (depth can be >2 also):

p:((`g;`d1`d2);(`r;enlist `e1);(`r;enlist `p1)) 

How to add an element to each element of the nested list but retaining the original structure; e.g. adding `h to each element of p to get the following :

((`g`h;(`d1`h;`d2`h));(`r`h;enlist `e1`h);(`r`h;enlist `p1`h)) 

I tried this but doesn't give what I want :

q)p,/:`h ((`g;`d1`d2;`h);(`r;enlist `e1;`h);(`r;enlist `p1;`h))  q)raze

,/:`h (`g`h;`d1`d2`h;`r`h;`e1`h;`r`h;`p1`h)


You can use .z.s to recursively go through the nested list and only append `h to lists of symbols:

q){$[0=type x;.z.s'[x];x,/:`h]}p g    h    d1 h d2 h `r`h      ,`e1`h `r`h      ,`p1`h 

For this function I have made the assumption that your nested lists will only contain symbols. It checks the type of the list, if it is not a mixed list then it appends `h to each element. If it is a mixed list then it passes each element of that list back into the function separately to check again.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: