简体   繁体   English

F#中的集合交集

[英]intersection of sets in F#

In an attempt to understand one of the answers from this question . 为了理解这个问题的答案之一。 I edited the code to look like this however it only returns [] 我编辑了代码,使其看起来像这样,但是它只返回[]

let rec intersect a b =
    let L1 = List.sort(a)
    let L2 = List.sort(b)
    match L1 with
    |h::t -> match L2 with
             |h2::t2 -> 
                 if h=h2 then h::(intersect t t2)
                 else if h>h2 then intersect t L2 else intersect L1 t2
             |[] -> []
    |[] -> [];;

intersect [1;2;3] [2;3;4]

What do I need to change to make it return a list (set) of intersecting values? 我需要更改什么才能使其返回相交值列表(一组)?

The intersection of 2 lists can be found by using the Set type. 可以使用Set类型找到2个列表的交集。 Which is basically an immutable HashSet. 这基本上是一个不变的HashSet。

let a = [1;2;3]
let b = [2;3;4]
let intersect a b = Set.intersect (set a) (set b) |> Set.toList

Edit: 编辑:

Shredderroy is correct that your logic is swapped between your else if & else condition. Shredderroy是正确的,如果&else条件在您的else之间交换了逻辑。 Also as an intro to F# recursion you shouldn't have a return like h::(intersect t t2) since this is not proper tail recursion and could lead to a stack overflow if the lists are long enough. 另外,作为F#递归的介绍,您不应像h::(intersect t t2)这样返回,因为这不是正确的尾递归,如果列表足够长,则可能导致堆栈溢出。 The closest I could get to your original code with proper tail recursion is : 我可以通过正确的尾部递归最接近您的原始代码的是:

let intersect a b =
    let rec loopy L1 L2 acc =
        match L1 with
        |h::t -> 
            match L2 with
            |h2::t2 -> 
                if h=h2 then 
                    loopy t t2 (h::acc)
                elif h>h2 then 
                    loopy L1 t2 acc
                else 
                    loopy t L2 acc
                 |[] -> List.rev acc
        |[] -> List.rev acc
    loopy (List.sort a) (List.sort b) []

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM