Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
List 将列表拆分为列表列表,列表作为拆分OCaml位置的参数_List_Split_Ocaml_Nested Lists - Fatal编程技术网

List 将列表拆分为列表列表,列表作为拆分OCaml位置的参数

List 将列表拆分为列表列表,列表作为拆分OCaml位置的参数,list,split,ocaml,nested-lists,List,Split,Ocaml,Nested Lists,我是OCaml新手,对如何编写一个名为separate_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.exi

我是OCaml新手,对如何编写一个名为separate_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返回列表的第一个子列表,因此我继续使用列表的其余部分构建列表,最后得到结果*)

注意:我看到您的函数名以大写字母开头。所有以大写字母开头的变量在Ocaml中表示“类型”,因此函数名应以小写字母开头可能是您的问题?

您可以尝试以下方法:

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

顺便说一句,函数名在OCaml中不能大写:)您尝试了什么,它似乎有什么问题?太棒了!你知道有没有办法用List.fold_left来代替递归吗?@V.Michel的ansew比我的好。事实上,你可以用
@
来使用List.fold_left,或者用
来使用List.fold_right::
就像Michel在
else(res,x::acc)
中那样,你可以用
else(res,acc@[x]来改变List.fold_left)
您应该更改fold_left中参数的顺序。我添加了一个新案例。Zhenyu的答案更清楚,但我想知道如何将其转换为fold格式
# 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)