Created
February 25, 2016 06:23
-
-
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.
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
-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