list - 两个列表按顺序并集 f#

标签 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)

但是,这并没有给我想要的结果;我希望结果按最小的第一个顺序排列。我该如何去做呢?

最佳答案

如果两个参数已经排序,那么您可以迭代它们并向结果添加较小的元素:

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/

相关文章:

linux - list_for_each_entry 重置游标

python - 如何将字符串格式化为两列列表

Python:当满足条件时如何将文本文件中的数字与字符串相加

F# 通用函数计算均值

f# - 无法在 F# 中扩展运算符?

f# - 在 F# 中将 native 指针与 WriteableBitmap 结合使用

java - 如何从 Java 中的列表集中删除重复项

database - 你如何从Android中的sqlite数据库中制作多项选择列表?

F#:通常不应重新定义 '&' 运算符

f# - 带有类型提供者的可移植库