I am new to OCaml and curious as to how to write a function called Seperate_by
that takes in two parameters, a list and a list of elements on where to split the original list.
For example,
Seperate_by [1;2;3;4;5;6;7] [3;5]
Should have an output of [[1;2];[4];[6;7]]
.
You can try this :
let seperate_by l lsep =
let add acc res = if acc<>[] then acc::res else res in
let(res,acc)=
List.fold_right ( fun x (res,acc) ->
if List.exists ((=)x) lsep then (add acc res,[]) else (res,x::acc)
) l ([],[])
in
add acc res
Test :
# seperate_by [1;2;3;4;5;6;7] [3;5];;
- : int list list = [[1; 2]; [4]; [6; 7]]
# seperate_by [1;2;3;4;5;6;7] [3;5;7];;
- : int list list = [[1; 2]; [4]; [6]]
# seperate_by [1;2;3;4;5;6;7] [1;5;7];;
- : int list list = [[2; 3; 4]; [6]]