Skip to content

Instantly share code, notes, and snippets.

@jotterbach
Last active February 13, 2018 18:14
Show Gist options
  • Select an option

  • Save jotterbach/d0d7cdcc98431eb3a3db909d79e212b2 to your computer and use it in GitHub Desktop.

Select an option

Save jotterbach/d0d7cdcc98431eb3a3db909d79e212b2 to your computer and use it in GitHub Desktop.
Run-Length Encoding in OCaml
(*
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