I found the answer in this post very interesting to do what I need, but I would like something where I could provide a list to be modified
, a list with values
that will be added and a list with the positions
of the values to be added.
Something to get this result:
listaInicial = {0, 1, 2, 3, 4, 5, 6, 7};
listaModificadora = {a, b, c, d, e};
listaPosições = {2, 6, 7, 8, 13};
Fold[Insert[#, #2[[1]], #2[[2]]] &, listaInicial, {{a, 2}, {b, 6}, {c,
7}, {d, 8}, {e, 13}}]
{0,a,1,2,3,b,c,d,4,5,6,7,e}
P.S:I think it should be very obvious, but I am still suffering with Slot function. One day I will be able to understand this function with a lot of training.
Answer
You can start applying Transpose
function:
listaInicial = {0, 1, 2, 3, 4, 5, 6, 7};
listaModificadora = {a, b, c, d, e};
listaPosições = {2, 6, 7, 8, 13};
Fold[Insert[#, #2[[1]], #2[[2]]] &, listaInicial,
Transpose[{listaModificadora, listaPosições}]]
{0,a,1,2,3,b,c,d,4,5,6,7,e}
Or
InsertValuePosition[list_, values_, positions_] :=
Fold[Insert[#, #2[[1]], #2[[2]]] &, list,
Transpose[{values, positions}]]
InsertValuePosition[listaInicial,listaModificadora,listaPosições]
{0,a,1,2,3,b,c,d,4,5,6,7,e}
Comments
Post a Comment