Skip to content

Instantly share code, notes, and snippets.

@vysakh0
Last active September 4, 2016 08:31
Show Gist options
  • Save vysakh0/609869f6283a2cdc7079 to your computer and use it in GitHub Desktop.
Save vysakh0/609869f6283a2cdc7079 to your computer and use it in GitHub Desktop.
Run length encoding in elixir
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
defmodule RunlengthTest do
use ExUnit.Case
test "run length encoding" do
assert Runlength.encode("AABBBCCCC") == "2A3B4C"
end
end
@andrewshatnyy
Copy link

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.

@vysakh0
Copy link
Author

vysakh0 commented Feb 8, 2016

@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"

@andrewshatnyy
Copy link

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