Skip to content

Instantly share code, notes, and snippets.

@22a
Created June 8, 2017 23:45
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 22a/7649f74dc79115fadcc618d8d8146d1a to your computer and use it in GitHub Desktop.
Save 22a/7649f74dc79115fadcc618d8d8146d1a to your computer and use it in GitHub Desktop.
Functional Katas, Elixir Special! 8-6-2017
defmodule Runlength do
def encode(string) do
String.codepoints(string)
|> List.foldl([], &count/2)
|> List.foldr("", &format/2)
end
defp count(char, [{char,n}|tail]) do
[{char, n+1}|tail]
end
defp count(char, acc) do
[{char, 1}|acc]
end
defp format({char, occ}, output) do
output <> Integer.to_string(occ) <> char
end
def decode(string) do
String.codepoints(string)
|> expand("")
end
defp expand([], acc) do acc end
defp expand([occ,char|tail], acc) do
String.duplicate(char, String.to_integer(occ)) <> expand(tail, acc)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment