Last active
November 22, 2017 16:34
-
-
Save actionshrimp/7a644bd411e78bee4fc47757ee33e5d4 to your computer and use it in GitHub Desktop.
Contiguous List.partition_by 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
(* 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