Skip to content

Instantly share code, notes, and snippets.

@soarez
Created January 13, 2015 12:21
Show Gist options
  • Save soarez/c508ff9a7a97a507ec52 to your computer and use it in GitHub Desktop.
Save soarez/c508ff9a7a97a507ec52 to your computer and use it in GitHub Desktop.
challenge.erl
-module(challenge).
-export([ swap/3 ]).
% no effect on an empty list
swap([ ], _, _) -> [ ];
% no effect on a list with a single item
swap([ H | [] ], _, _) -> [ H ];
% no effect when both indexes are the same
swap(List, X, X) -> List;
swap([ H | T ], 0, IndexB) -> [ find(T, IndexB - 1) | replace(T, IndexB - 1, H) ];
swap([ H | T ], IndexA, 0) -> [ find(T, IndexA - 1) | replace(T, IndexA - 1, H) ];
swap([ H | T ], IndexA, IndexB) ->
[ H | swap(T, IndexA - 1, IndexB -1) ].
% returns an element from a a list at Index
find([ ], _) -> error(badIndex);
find([ H | _ ], 0) -> H;
find([ _ | T ], Index) -> find(T, Index - 1).
% returns a list with the element at Index replaced by New
replace([ ], _, _) -> error(badIndex);
replace([ _ | T ], 0, New) -> [ New | T ];
replace([ H | T ], Index, New) -> [ H | replace(T, Index - 1, New) ].
@tdantas
Copy link

tdantas commented Jan 13, 2015

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment