Efficient list rotation

Vladimir Sekissov <>
Fri Apr 15 11:52:39 CEST 2005


Good day,

joelr1> -module(bar).
joelr1> -compile([export_all]).
joelr1> 
joelr1> rotate(_Target, []) ->
joelr1>     [];
joelr1> 
joelr1> rotate(Target, [H|T]) ->
joelr1>     rotate(Target, [H|T], none).
joelr1> 
joelr1> rotate(Target, [H|T], none) when Target =:= H ->
joelr1>     rotate(Target, T, H);
joelr1> 
joelr1> rotate(Target, [H|T], none) ->
joelr1>     rotate(Target, T ++ [H], none);
joelr1> 
joelr1> rotate(_Target, [], X) ->
joelr1>     [X];
joelr1> 
joelr1> rotate(_Target, [H|T], X) ->
joelr1>     [H|T] ++ [X].

rotate(Target, L) ->
    {Before, FromToEnd} =
          lists:splitwith(fun (E) -> E =/= Target end, L),
    case FromToEnd of
       [Target|T] ->
         T ++ lists:reverse([T|Before]);
       _ ->
         lists:reverse(L)
    end.

Best Regards,
Vladimir Sekissov



More information about the erlang-questions mailing list