Skip to content

Instantly share code, notes, and snippets.

@tdantas
Created January 13, 2015 21:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tdantas/417d172ad8c10d5cec7a to your computer and use it in GitHub Desktop.
Save tdantas/417d172ad8c10d5cec7a to your computer and use it in GitHub Desktop.
Swap elixir
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