Created
January 13, 2015 21:04
-
-
Save tdantas/417d172ad8c10d5cec7a to your computer and use it in GitHub Desktop.
Swap elixir
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Swap do | |
def of([ ], _, _), do: [ ] | |
def of(list, left, left), do: list | |
def of(list, left, right) do | |
list | |
|> List.replace_at(left, nth(list, right)) | |
|> List.replace_at(right, nth(list, left)) | |
end | |
def nth(list, idx) when is_number(idx) and idx < 0 do | |
throw 'Index must be positive' | |
end | |
def nth(list, idx) when idx > length(list) - 1 do | |
throw ' index bigger the list size' | |
end | |
def nth([ element | _ ] , 0), do: element | |
def nth([ head | tail ], idx), do: nth(tail, idx - 1) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment