Last active
September 22, 2020 20:47
-
-
Save awostenberg/0ae283d6c718b43b021ce3f43080539b to your computer and use it in GitHub Desktop.
run length encoding with a fold
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
//remove consecutive duplicates | |
let uniq items = | |
let uniq accum item = | |
match accum with | |
| a::_ when a = item -> accum | |
| _ -> item::accum | |
items |> List.fold uniq [] |> List.rev | |
let uniq_tests = | |
[ | |
uniq [] |> List.isEmpty | |
uniq ['a'] = ['a'] | |
uniq ['a';'b'] = ['a';'b'] | |
uniq ['a';'a'] = ['a'] | |
] | |
//run length encoding | |
let rle items = | |
let rle accum item = | |
match accum with | |
| (count,a)::rest when a=item -> (count+1,item)::rest | |
| _ -> (1,item)::accum | |
items |> List.fold rle [] |> List.rev | |
let rle_tests = | |
[ | |
rle [] = [] | |
rle ['a'] = [(1,'a')] | |
rle ['a';'b'] = [(1,'a');(1,'b')] | |
rle ['a';'a'] = [(2,'a')] | |
rle ['a';'b';'b';'c'] = [(1, 'a'); (2, 'b'); (1, 'c')] | |
] | |
// if we sort, we have histogram | |
["hello";"world";"hello"] |> List.sort |> rle |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment