Last active
February 13, 2018 18:14
-
-
Save jotterbach/d0d7cdcc98431eb3a3db909d79e212b2 to your computer and use it in GitHub Desktop.
Run-Length Encoding in OCaml
This file contains hidden or 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
| (* | |
| This is a simple solution to the Run-Length Encoding problem described | |
| in Watrophy #24 (http://www.watrophy.com/posts/24-Run-Length-Encoding.html) | |
| *) | |
| open Core | |
| let rle int_list = | |
| let increment tup n = | |
| match tup with | |
| | (k, v) -> if k = n then [(k, v+1)] else [(n, 1); (k,v)] in | |
| let increment_if_match accum n = | |
| match List.rev accum with | |
| | [] -> [(n, 1)] | |
| | hd :: tl -> List.rev ( (increment hd n) @ tl ) in | |
| List.fold_left int_list ~init:[] ~f:increment_if_match |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment