将整数列表拆分为列表元组

时间:2015-11-14 18:25:59

标签: f# ocaml

在OCaml 中浪费了几个小时尝试完成此任务,但无法弄清楚语法错误。

let split l =
  let rec split1 (l1, l2) accu = 
    match (l1, l2) with
    | xs, ([] | [_]) -> (accu, xs)
    | [], _ -> ([], [])
    | x::xs, y::y'::ys -> split1 (xs, ys) x::accu
  split1 (l, l) [];;

我在第7行遇到语法错误,字符20-22

但是F#中的类似代码编译并执行正常:

    let split (l :int list) =
      let rec split1 (l1 :int list, l2 :int list) (accu :int list) = 
        match (l1, l2) with
        | xs, ([] | [_]) -> (rev accu, xs)
        | [], _ -> ([], [])
        | x::xs, y::y'::ys -> let t = x::accu in split1 (xs, ys) t
    split1 (l, l) [];;

在[1; 2; 3; 4; 5; 6; 7; 8; 9; 1; 2; 34; 5; 6]列表中以F#运行

我得到了结果:

([1; 2; 3; 4; 5; 6; 7],[8; 9; 1; 2; 34; 5; 6])

我正在使用基于Web的TryOcaml(v.4.01.0)

提前感谢您的帮助

1 个答案:

答案 0 :(得分:3)

let split (l :int list) =
      let rec split1 ((l1 :int list), (l2 :int list)) (accu :int list) =
        match (l1, l2) with
        | xs, ([] | [_]) -> (List.rev accu, xs)
        | [], _ -> ([], [])
        | x::xs, y::y'::ys -> let t = x::accu in split1 (xs, ys) t
      in
    split1 (l, l) []

或者

let split l  =
      let rec split1 (l1, l2 ) accu  =
        match (l1, l2) with
        | xs, ([] | [_]) -> (List.rev accu, xs)
        | [], _ -> ([], [])
        | x::xs, y::y'::ys -> split1 (xs, ys) (x::accu)                   
      in
    split1 (l, l) []

测试:

# split [1;2;3;4;5;6;7;8;9;1;2;34;5;6];;
- : int list * int list = ([1; 2; 3; 4; 5; 6; 7], [8; 9; 1; 2; 34; 5; 6])