2012-11-23 46 views
2

我有這樣的代碼,團結兩個列表:聯盟爲了兩份名單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) 

然而,這並沒有給我結果,我想;我希望結果按照最小的順序排列。我會如何去做這件事?

+0

可能的重複:http://stackoverflow.com/questions/4100251/merge-two-lists-in-f-recursively – bytebuster

+0

@bytebuster我只在尋找單詞聯合,當我搜索它,我的壞。該代碼幫助了很多,但名單[4; 3; 2]和[8; 7; 6]不起作用 – user1838768

回答

0

這會工作,即使你的輸入進行排序:

let sortedUnion list1 list2 = 
    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 unsorted = union list1 list2 
    List.sort unsorted 
+0

有沒有辦法做到沒有重複? – user1838768

+0

您的代碼已經刪除了重複項,假設'mem x list1'檢查'x'是否是'list1'的成員。 –

2

如果兩個參數已經排序比你可以遍歷他們與添加小元素結果:

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)