2

I have this code that unites two lists:

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

However, this doesn't give me the result I would like; I want the result to be in order with the smallest first. How would I go about doing this?

Alexander R
  • 2,468
  • 24
  • 28
user1838768
  • 143
  • 1
  • 7

2 Answers2

2

If the two arguments are already sorted than you can just iterate over both of them and add smaller elements to the result:

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)
Tomas Petricek
  • 240,744
  • 19
  • 378
  • 553
0

This will work even if your inputs are not sorted:

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
Mark Pattison
  • 2,964
  • 1
  • 22
  • 42