将列表拆分为列表列表,列表作为拆分Ocaml

时间:2017-02-09 03:33:20

标签: list split ocaml nested-lists

我是Ocaml的新手,好奇如何编写一个名为Seperate_by的函数,它接受两个参数,一个列表和一个元素列表,分析原始列表的位置。

例如,

Seperate_by [1;2;3;4;5;6;7] [3;5]

输出应为[[1;2];[4];[6;7]]

提前致谢!

3 个答案:

答案 0 :(得分:0)

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返回列表的第一个sub_list,所以我继续用列表的其余部分构建列表,最后我们得到结果*)

注意:我看到你的函数名称以大写字母开头。所有变量以大写字母开头表示Ocaml中的'type',因此函数的名称应该以小写字母开头可能是你的问题?

答案 1 :(得分:0)

你可以试试这个:

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]]

答案 2 :(得分:0)

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)    
相关问题