Skip to content

Instantly share code, notes, and snippets.

@unix1
Created February 25, 2016 06:23
Show Gist options
  • Save unix1/81511daf0c4d96adc885 to your computer and use it in GitHub Desktop.
Save unix1/81511daf0c4d96adc885 to your computer and use it in GitHub Desktop.
Implementation of Run-length encoding algorithm in Erlang. Both encode and decode functions are provided. For more info see https://en.wikipedia.org/wiki/Run-length_encoding and http://rosettacode.org/wiki/Run-length_encoding - the latter has a couple of implementations in Erlang, but I like using lists:foldr/3 this way.
-module(rle).
-export([encode/1]).
-export([decode/1]).
encode(List) ->
lists:flatten(lists:foldr(
fun (Prev, [[Count, Prev]|Rest]) ->
[[Count + 1, Prev]|Rest];
(Current, Acc) ->
[[1, Current]|Acc]
end,
[],
List)).
decode(List) ->
decode(List, []).
decode([], Acc) ->
lists:reverse(Acc);
decode([Count|[Char|Rest]], Acc) ->
AccNew = lists:append(lists:duplicate(Count, Char), Acc),
decode(Rest, AccNew).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment