Skip to content

Instantly share code, notes, and snippets.

@tdantas

tdantas/swap.ex

Created Jan 13, 2015
Embed
What would you like to do?
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
You can’t perform that action at this time.