我有这段代码将两个列表结合起来:
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 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)
关于list - 两个列表按顺序并集 f#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13530495/