Skip to content

Instantly share code, notes, and snippets.

@actionshrimp
Last active November 22, 2017 16:34
Show Gist options
  • Save actionshrimp/7a644bd411e78bee4fc47757ee33e5d4 to your computer and use it in GitHub Desktop.
Save actionshrimp/7a644bd411e78bee4fc47757ee33e5d4 to your computer and use it in GitHub Desktop.
Contiguous List.partition_by OCaml
(* Split a list when the predicate changes when comparing two neighbours *)
let partition_by (predicate : 'a -> 'a -> bool) (xs : 'a list) : ('a list) list =
let rec go (cur_x, cur_xs, acc : 'a * ('a list) * (('a list) list)) (xs : 'a list) : ('a list) list =
match xs with
| [] -> (List.rev ((List.rev cur_xs) :: acc))
| x :: xs ->
if predicate x cur_x
then go (x, x :: cur_xs, acc) xs
else go (x, [x], (List.rev cur_xs) :: acc) xs
in
match xs with
| x :: xs -> go (x, [x], []) xs
| [] -> []
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment