1

Say I have a list (1 3 4) and after 1 I want to insert another element 2 resulting in (1 2 3 4).

How can this be done efficiently in a generic way?

Donald_W
  • 1,773
  • 21
  • 35
user3914448
  • 469
  • 1
  • 11
  • 22

2 Answers2

1

An alternative approach which allows for multiple inserts at once.

If the indices are to index the original list:

q){raze cut[(0,z);x],'(y,enlist ())}[til 10;999 998 994;2 4 8]
0 1 999 2 3 998 4 5 6 7 994 8 9

If the indices are to index consecutive iterations of the list:

q){raze cut[(0,z);x],'(y,enlist ())}/[til 10;999 998 994;2 4 8]
0 1 999 2 998 3 4 5 994 6 7 8 9
terrylynch
  • 11,844
  • 13
  • 21
0

I think you need to be more specific about what you want, but for now here's an example of how you could achieve it

q)list:1 3 4
q)list
1 3 4
q)list: asc list,:2
q)list
`s#1 2 3 4

Or another way is let's say you know the index at which you want to add the element to the list, in this case at index 1, then you could create a function as such:

q)add:{[lst;ele;ind] (ind#lst),ele,(ind _ lst)}
q)list:1 3 4
q)add[list;2;1]
1 2 3 4
zak.oud
  • 152
  • 1
  • 2
  • 6