Efficient list rotation

Joel Reymont joelr1@REDACTED
Fri Apr 15 10:41:03 CEST 2005


Folks,

Is there a more efficient version of this code? I understand that it's
better to append to the head of the list and reverse afterwards but
appending to the tail works with the logic of the task. 

I'm trying to rotate the list so that a particular item is at the tail of
the list, that is if I rotate the list once more it will be at the head.

As a bit of background info, I need this for my poker logic as when a
player makes a bet I rotate the list and place them at the tail. I might
delete them right after or I might not.

-module(bar).
-compile([export_all]).

rotate(_Target, []) ->
    [];

rotate(Target, [H|T]) ->
    rotate(Target, [H|T], none).

rotate(Target, [H|T], none) when Target =:= H ->
    rotate(Target, T, H);

rotate(Target, [H|T], none) ->
    rotate(Target, T ++ [H], none);

rotate(_Target, [], X) ->
    [X];

rotate(_Target, [H|T], X) ->
    [H|T] ++ [X].

    Thanks, Joel

-- 
http://wagerlabs.com/tech





More information about the erlang-questions mailing list