Skip to content

Instantly share code, notes, and snippets.

@winny-
Created May 14, 2018 02:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save winny-/2558a4a97ac41e3514bd5c703cf420f2 to your computer and use it in GitHub Desktop.
Save winny-/2558a4a97ac41e3514bd5c703cf420f2 to your computer and use it in GitHub Desktop.
(* Mine *)
let encode list =
let rec encode' current acc list =
match (current, list) with
| (None, []) -> acc
| (Some c, []) -> c::acc
| (None, h::t) -> encode' (Some (1, h)) acc t
| (Some ((count, elem) as c), h::t) -> if elem = h
then encode' (Some (count+1, elem)) acc t
else encode' (Some (1, h)) (c::acc) t
in List.rev (encode' None [] list);;
(* Theirs *)
let encode list =
let rec aux count acc = function
| [] -> [] (* Can only be reached if original list is empty *)
| [x] -> (count+1, x) :: acc
| a :: (b :: _ as t) -> if a = b then aux (count + 1) acc t
else aux 0 ((count+1,a) :: acc) t in
List.rev (aux 0 [] list);;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment