[erlang-questions] Swap 2 elements within a list a la Erlang ?

Andreas Bakurov andreasmk2@REDACTED
Sat Jun 9 11:34:20 CEST 2007


Hello all. I am new to Erlang and face a lot of  dilemmas.
I have implemented Knuth's or Fisher-Yates shuffle in Erlang
http://www.nist.gov/dads/HTML/fisherYatesShuffle.html
, The main mechanism of this algorithm is swapping  two elements within 
a list : what I wrote is

% For A < B
swap_elements(A, B, List) ->
    {P1,T1} = lists:split(A - 1, List),
    [Elem1 | T2] = T1,
    {P2, T3} = lists:split(B - length(P1) - 2, T2), % -2 is because we 
removed 1 element from T2 and one less 1 because of 0 based index
    [Elem2 | P3] = T3,
    lists:flatten([P1, Elem2, P2, Elem1, P3]).

It splits a list in 5 parts two are element the rest are the parts 
surrounding them. Then puts the parts at the same places and elements in 
inverse order.

It works but it seems ugly to me and not in a spirit of functional 
programming , furthermore it is slow for lists of 10000 elements and more.
Is there a more elegant way to write this function ? If yes, please send 
me an example...

--Sincerely
Andreas



More information about the erlang-questions mailing list