簡體   English   中英

F#中的集合交集

[英]intersection of sets in F#

為了理解這個問題的答案之一。 我編輯了代碼,使其看起來像這樣,但是它只返回[]

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]

我需要更改什么才能使其返回相交值列表(一組)?

可以使用Set類型找到2個列表的交集。 這基本上是一個不變的HashSet。

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

編輯:

Shredderroy是正確的,如果&else條件在您的else之間交換了邏輯。 另外,作為F#遞歸的介紹,您不應像h::(intersect t t2)這樣返回,因為這不是正確的尾遞歸,如果列表足夠長,則可能導致堆棧溢出。 我可以通過正確的尾部遞歸最接近您的原始代碼的是:

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