Skip to content

Instantly share code, notes, and snippets.

@ijoshsmith
Created February 20, 2015 01:41
Show Gist options
  • Save ijoshsmith/2ca91f5ae02b98cf2848 to your computer and use it in GitHub Desktop.
Save ijoshsmith/2ca91f5ae02b98cf2848 to your computer and use it in GitHub Desktop.
Encode a list using Elixir
# I wrote this after watching Dave Thomas review his implementation
# in this presentation: https://www.youtube.com/watch?v=5hDVftaPQwY
defmodule MyList do
def encode(list), do: _encode(list, [])
defp _encode([ a, a | tail], acc), do: _encode([ {a, 2} | tail], acc)
defp _encode([{a, n}, a | tail], acc), do: _encode([{a, n+1} | tail], acc)
defp _encode([{a, n}, b | tail], acc), do: _encode([ b | tail], [{a, n} | acc])
defp _encode([ a, b | tail], acc), do: _encode([ b | tail], [ a | acc])
defp _encode([ a], acc), do: _encode([ ], [ a | acc])
defp _encode([ ], acc), do: Enum.reverse acc
end
IO.inspect [8, 8, 8, 8, 8, 8, 7, 5, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0] |> MyList.encode
# prints: [{8, 6}, 7, {5, 3}, {0, 9}]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment