[erlang-questions] re moving nth element from a list

anupamk <>
Tue Jun 24 16:40:08 CEST 2008


hi all,

can you please let me know what would be a more efficient approach to
removing nth element from a list.

here are 2 versions that i have come up with:

,----
| %% remove nth element from a list
| remove_nth(L, N) ->
|     do_remove_nth(L, N, 1, []).
|
| do_remove_nth([_ | Rest], N, Start, Result) when N =:= Start ->
|     do_remove_nth(Rest, N, Start+1, Result);
|
| do_remove_nth([First | Rest], N, Start, Result) ->
|     do_remove_nth(Rest, N, Start+1, [First | Result]);
|
| do_remove_nth([], _, _, Result) ->
|     lists:reverse(Result).
|
| remove_nth_2(L, N) ->
|     {Split_left, Split_right} = lists:split(N, L),
|
|     lists:append(lists:sublist(Split_left, length(Split_left)-1),
|                  lists:sublist(Split_right, length(Split_right))).
`----

i will be more than happy to know of other approaches to do the same
too.

thanks
kind regards
anupam

ps: i posted this message earlier, but i didn't see it appear on the list.
apologies if there are multiple copies of it.
-- 
View this message in context: http://www.nabble.com/removing-nth-element-from-a-list-tp18092530p18092530.html
Sent from the Erlang Questions mailing list archive at Nabble.com.




More information about the erlang-questions mailing list