两个列表之间的交集F# [英] Intersection between two lists F#

查看:77
本文介绍了两个列表之间的交集F#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个使用两个列表之间的交点并创建一个新列表的函数,我有这个函数:let intersect x y = Set.intersect (Set.ofList x) (Set.ofList y)可以执行我想要的操作,但是我不想使用F#中的任何内置函数

I am looking for a function that takes the intersection between two lists and creates a new list, I have this function: let intersect x y = Set.intersect (Set.ofList x) (Set.ofList y) that do what I ant but I dont want to use any of the inbuilt functions in F#

推荐答案

最好使用库中的东西,但是如果不能

It is best to use the library stuff, but if you can't

如果我们假设输入列表已排序(使用List.sort或编写自己的列表):

If we assume that the input lists are sorted (use List.sort or write your own) :

let rec intersect a b =
    match a with
    |h::t -> match b with
             |h2::t2 -> 
                 if h=h2 then h::(intersect t t2)
                 else if h>h2 then intersect t b else intersect a t2
             |[] -> []
    |[] -> []

这篇关于两个列表之间的交集F#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆