【问题标题】:Splitting a List of integers into a tuple of lists将整数列表拆分为列表元组
【发布时间】:2015-11-14 18:25:59
【问题描述】:

浪费了几个小时试图在 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)

提前感谢您的帮助

【问题讨论】:

    标签: f# ocaml


    【解决方案1】:
    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])
    

    【讨论】:

      猜你喜欢
      • 2019-10-20
      • 2012-03-21
      • 1970-01-01
      • 2017-07-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-27
      • 1970-01-01
      相关资源
      最近更新 更多