将列表拆分为列表列表,其中一个列表作为 OCaml 拆分位置的参数
Split list into list of lists with a list as a parameter for where to split OCaml
我是 OCaml 的新手,很好奇如何编写一个名为 Seperate_by
的函数,它接受两个参数,一个列表和一个元素列表,用于拆分原始列表。
例如,
Seperate_by [1;2;3;4;5;6;7] [3;5]
应该有 [[1;2];[4];[6;7]]
的输出。
let rec seperate_by l sign=
let rec aux2 = function
(head,[])->(head,[])
|(head,x::r) -> if List.exists ((=) x) sign then (head,r)
else aux2 (head@[x],r)
in
let res = aux2 ([],l) in
match res with
|(head,[])->head::[]
|(sub_list,rest_list) -> (sub_list)::(split rest_list sign)
;;
(*函数 aux2 returns 列表的第一个 sub_list 所以我继续用列表的其余部分构建列表,最后我们得到结果 *)
注意:我看到你的函数名以 bt 开头 uppercase.All 变量以大写字母开头意味着 Ocaml 中的 'type',所以函数名应该以小写字母开头可能是你的问题?
你可以试试这个:
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
测试:
# 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]]
let rec seperate_by l sign=
let rec aux2 = function
(head,[])->(head,[])
|(head,x::y::r) when x=y -> if List.exists ((=) x) sign then (head@[],y::r) else aux2 (head@[x],y::r)
|(head,x::r) -> if List.exists ((=) x) sign then (head,r) else aux2 (head@[x],r)
in
let res = aux2 ([],l)
in
match res with
|(head,[])->head::[]
|(sub_list,rest_list) -> (sub_list)::(seperate_by rest_list sign)
我是 OCaml 的新手,很好奇如何编写一个名为 Seperate_by
的函数,它接受两个参数,一个列表和一个元素列表,用于拆分原始列表。
例如,
Seperate_by [1;2;3;4;5;6;7] [3;5]
应该有 [[1;2];[4];[6;7]]
的输出。
let rec seperate_by l sign=
let rec aux2 = function
(head,[])->(head,[])
|(head,x::r) -> if List.exists ((=) x) sign then (head,r)
else aux2 (head@[x],r)
in
let res = aux2 ([],l) in
match res with
|(head,[])->head::[]
|(sub_list,rest_list) -> (sub_list)::(split rest_list sign)
;;
(*函数 aux2 returns 列表的第一个 sub_list 所以我继续用列表的其余部分构建列表,最后我们得到结果 *)
注意:我看到你的函数名以 bt 开头 uppercase.All 变量以大写字母开头意味着 Ocaml 中的 'type',所以函数名应该以小写字母开头可能是你的问题?
你可以试试这个:
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
测试:
# 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]]
let rec seperate_by l sign=
let rec aux2 = function
(head,[])->(head,[])
|(head,x::y::r) when x=y -> if List.exists ((=) x) sign then (head@[],y::r) else aux2 (head@[x],y::r)
|(head,x::r) -> if List.exists ((=) x) sign then (head,r) else aux2 (head@[x],r)
in
let res = aux2 ([],l)
in
match res with
|(head,[])->head::[]
|(sub_list,rest_list) -> (sub_list)::(seperate_by rest_list sign)