type a = A of int | B of int list | C | D
Now I have an a list
, and want to partition it to a list list
that is each list has only on kind of the union type, while preserving the order:
e.g. an input of [A 1; C; B [1;2]; A 2; C; A 3; D; B [2;3]]
gives
[[A 1; A 2; A 3]; [B [1;2]; B [2;3]]; [C; C]; [D]]
.
I know it can be done by doing multiple List.filter
, and if efficiency is the concern there’re serval ways to hand code the filtering so it would only traverse the list once like the following when the data type is known, and the number if filters are fixed to three:
let trivial, normal, complete =
List.fold_left (fun (t, n, c) tac ->
let tac = mapT tac in
match tac.auto_type with
AutoTrivial -> tac::t, n, c
| AutoNormal -> t, tac::n, c
| AutoComplete -> t, n, tac::c
) ([],[],[]) tactics
but I would like to know if there’s a generic way to parametrize the filtering while both the data type and number of filters is unspecified.
Or are there any data structures can memo the result of filtering a list, and supports map
to sublists of arbitrary combinations of tags?