f#顺序的两个列表的联合

时间:2012-11-23 13:53:38

标签: list f#

我有这个代码将两个列表联合起来:

let rec union list1 list2 =
    match list2 with
    | [] -> list1
    | x::xs when mem x list1 -> union list1 xs
    | x::xs -> x::(union list1 xs)

然而,这并没有给我我想要的结果;我希望结果与最小的结果一致。我该怎么做呢?

2 个答案:

答案 0 :(得分:2)

如果两个参数已经排序,那么你可以迭代它们并将更小的元素添加到结果中:

let rec union list1 list2 =
    match list1, list2 with
    | [], other | other, [] -> other
    | x::xs, y::ys when x < y -> x :: (union xs list2)
    | x::xs, y::ys -> y :: (union list1 ys)

答案 1 :(得分:0)

即使您的输入未排序,这也会有效:

let sortedUnion list1 list2 =
    let rec union list1 list2 =
        match list2 with
        | [] -> list1
        | x::xs when mem x list1 -> union list1 xs
        | x::xs -> x::(union list1 xs)
    let unsorted = union list1 list2
    List.sort unsorted