【问题标题】:OCaml recursive function int list -> int -> (int list * int list)OCaml 递归函数 int list -> int -> (int list * int list)
【发布时间】:2014-03-06 22:33:54
【问题描述】:

正在准备期中考试,正在查看一些旧的考试题。这个没有发布解决方案,让我很困惑:

partition: int list -> int -> (int list * int list) 将它的 第一个参数到两个列表中,一个包含所有小于 它的第二个参数,以及其他所有大于或的元素 等于它的第二个参数。 partition [5;2;10;4] 4 = ([2], [5;10;4])

哦,我应该能够找到解决方案不使用辅助功能

这是我所得到的:

let rec partition l n = match l with 
    | [] -> ([], []) (* must return this type *)
    | x :: xs -> if x < n then (* append x to first list, continue recursing *)
                    else (* append x to second list, continue recursing *)

通常,我会使用带有额外参数的 aux 函数来存储我正在构建的一对列表,但这不能在这里完成。我有点卡住了

【问题讨论】:

    标签: ocaml


    【解决方案1】:

    您应该使用let in 构造来匹配递归调用的返回值:

    let rec partition l n = match l with 
        | [] -> ([], [])
        | x :: xs -> let a, b = partition xs n in
                        if x < n then (x::a), b
                        else          a, (x::b);;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多