Created
June 8, 2017 23:45
-
-
Save 22a/7649f74dc79115fadcc618d8d8146d1a to your computer and use it in GitHub Desktop.
Functional Katas, Elixir Special! 8-6-2017
This file contains 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 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