user9499460
user9499460

Reputation:

Applying an operation on each element of nested list

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[p],\:`h
(`g`h;`d1`d2`h;`r`h;`e1`h;`r`h;`p1`h)

Upvotes: 1

Views: 979

Answers (3)

terrylynch
terrylynch

Reputation: 13572

Although not recursive (and so requires some knowledge about the shape of your nested list), a more conventional approach would be

q).[p;2#(::);,';`h]
g    h    d1 h d2 h
`r`h      ,`e1`h
`r`h      ,`p1`h

Upvotes: 2

nyi
nyi

Reputation: 3229

Though Thomas has already answered the question; In case you want to specify any other operation apart from append, you can use the following :

q)f:{`$ "_" sv string x,y}

q){[o;a;e] $[-11<>type e; .z.s [o;a] each e; o[e;a]] }[f;`h] each p
`g_h `d1_h`d2_h
`r_h ,`e1_h
`r_h ,`p1_h

or when f is assigned as append operation

q)f:{x,y}
q){[o;a;e] $[-11<>type e; .z.s [o;a] each e; o[e;a]] }[f;`h] each p
g    h    d1 h d2 h
`r`h      ,`e1`h
`r`h      ,`p1`h

Upvotes: 1

Thomas Smyth
Thomas Smyth

Reputation: 5644

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.

Upvotes: 4

Related Questions