2011-11-06 67 views
2

我有4個不同數據的數組。對於字符串的第一個數組,我想刪除重複的元素並獲得具有4個元素的唯一元組數組的結果。 例如,假設數組是:F#進一步要求查找唯一的元組數組

let dupA1 = [| "A"; "B"; "C"; "D"; "A" |] 
let dupA2 = [| 1; 2; 3; 4; 1 |] 
let dupA3 = [| 1.0M; 2.0M; 3.0M; 4.0M; 1.0M |] 
let dupA4 = [| 1L; 2L; 3L; 4L; 1L |] 

我想要得到的結果是:

let uniqueArray = [| ("A", 1, 1.0M, 1L); ("B", 2, 2.0M, 2L); ("C", 3, 3.0M, 3L); ("D",4, 

感謝abatishchev他的偉大的代碼,現在我有這樣的回答:

let zip4 a (b : _ []) (c : _ []) (d : _ []) = 
    Array.init (Array.length a) (fun i -> a.[i], b.[i], c.[i], d.[i]) 
let uniqueArray = zip4 dupA1 dupA2 dupA3 dupA4 |> Seq.distinct |> Seq.toArray 

但是,更進一步,我想從唯一數組中找到每個數組的結果。

let uniqueArray = [| ("A", 1, 1.0M, 1L); ("B", 2, 2.0M, 2L); ("C", 3, 3.0M, 3L); ("D",4, 4.0M, 4L) |] 

我想下面的4列從uniqeArray:

let uniqA1 = [| "A"; "B"; "C"; "D" |] 
let uniqA2 = [| 1; 2; 3; 4 |] 
let uniqA3 = [| 1.0M; 2.0M; 3.0M; 4.0M |] 
let uniqA4 = [| 1L; 2L; 3L; 4L |] 

我嘗試下面的代碼:

let [| uniqA1, uniqA2, uniqA3, uniqA4 |] = uniqueArray 

首先,我得到的編譯器警告:

Warning 1
Incomplete pattern matches on this expression. For example, the value ' [|_; _|] ' may indicate a case not covered by the pattern(s).

我使用之後,在運行時,我得到了以下錯誤:

Microsoft.FSharp.Core.MatchFailureException was unhandled 
Message: An unhandled exception of type 'Microsoft.FSharp.Core.MatchFailureException' occurred in Program.exe 

請幫我進一步的要求。

+0

如果你與你前面的問題做,你應該標記一個答案是正確的。 –

+2

abatishchev沒有寫這個代碼。這是@Ramon Snir誰寫的代碼。請給予幫助你的學分。 – pad

+0

嗨, 比你的反饋,我可以犯錯誤的信用,我會改變它;但我看不出我如何將問題標記爲答案。 請給我一些指示。 再次感謝您的幫助! –

回答

3

現在需要unzip4

let unzip4 arr = 
    let a = Array.zeroCreate (Array.length arr) 
    let b = Array.zeroCreate (Array.length arr) 
    let c = Array.zeroCreate (Array.length arr) 
    let d = Array.zeroCreate (Array.length arr) 
    arr 
    |> Array.iteri (fun i (x, y, z, w) -> 
     a.[i] <- x 
     b.[i] <- y 
     c.[i] <- z 
     d.[i] <- w) 
    a, b, c, d 

然後,你可以這樣做:

> let uniqA1, uniqA2, uniqA3, uniqA4 = unzip4 uniqueArray;; 

val uniqA4 : int64 [] = [|1L; 2L; 3L; 4L|] 
val uniqA3 : decimal [] = [|1.0M; 2.0M; 3.0M; 4.0M|] 
val uniqA2 : int [] = [|1; 2; 3; 4|] 
val uniqA1 : string [] = [|"A"; "B"; "C"; "D"|] 
+0

你好, 非常感謝你的偉大代碼,它工作得很好。 但是,我仍然不知道如何將答案標記爲正確。 如果我知道我會做到這一點,並讚揚你的工作。 再次感謝您的及時幫助! 約翰 –

+0

在帖子的左側,有上/下箭頭,下方有一個概括的v按鈕。點擊按鈕(並按上箭頭,如果你想說答案很好!)接受答案。 –