Skip to content

Instantly share code, notes, and snippets.

@soarez soarez/challenge.erl
Created Jan 13, 2015

Embed
What would you like to do?
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

This comment has been minimized.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.