Last active
September 4, 2016 08:31
-
-
Save vysakh0/609869f6283a2cdc7079 to your computer and use it in GitHub Desktop.
Run length encoding in elixir
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(<< first :: binary-size(1) , rest :: binary>>) do | |
encode({first, 1}, rest, "") | |
end | |
def encode({letter, count}, << letter :: binary-size(1) , rest :: binary>>, result) do | |
encode({letter, count + 1}, rest, result) | |
end | |
def encode({letter, count}, << diff :: binary-size(1) , rest :: binary>>, result) do | |
result = result <> to_string(count) <> letter | |
encode({diff, 1}, rest, result) | |
end | |
def encode({letter, count}, <<>>, result) do | |
result <> to_string(count) <> letter | |
end | |
end |
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 RunlengthTest do | |
use ExUnit.Case | |
test "run length encoding" do | |
assert Runlength.encode("AABBBCCCC") == "2A3B4C" | |
end | |
end |
@andrewshatnyy The second method will match only if the first argument letter
variable and the second argument letter
variable are the same, otherwise it will match the third method. To give an example
defmodule Sample
def test(same, same), do: "Same arguments"
def test(same, diff), do: "Different arguments"
end
Sample.test(1, 1) #=> "Same arguments"
Sample.test(1, 5) #=> "Different arguments"
Oh right I see now. I misread the second definition. Cheers for example!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How does airity differs at the third function definition and the second from the top?
It looks like the third func would just never match.