OCaml递归函数int列表 - > int - > (int list * int list)

时间:2014-03-06 14:28:54

标签: ocaml

学习期中考试并正在查看一些旧的考试题目。这个没有发布解决方案并且让我感到困惑:

  

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函数来存储我正在构建的列表对,但这不能在这里完成。我有点卡住了

1 个答案:

答案 0 :(得分:2)

您应该使用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);;
相关问题