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

Peter Lund erlang@REDACTED
Wed Jun 25 09:59:22 CEST 2008


Use OTP stdlib!

Remove = R =
   fun(L,N) ->
       string:substr(L,1,N-1)++string:substr(L,N+1)
   end.

1> L=lists:seq(1,10).
[1,2,3,4,5,6,7,8,9,10]

2> R(L,2).
[1,3,4,5,6,7,8,9,10]

3> R(L,10).
[1,2,3,4,5,6,7,8,9]

4> R(L,1).
[2,3,4,5,6,7,8,9,10]

(if performance is an issue, measure different approaches)

/Peter

anupamk skrev:
> 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.
>   




More information about the erlang-questions mailing list