2011-12-21 178 views
1

我对F#相对来说比较新,但到目前为止它确实给我留下了深刻的印象,尽管我花了很多时间搜索并查看自己的书,但我还是无法找到一个例子以下: 我(在现实中或以上)3个从不同的输入源创建的列表:数据库,CSV文件等承担这些列表的结构如下:合并不同的“类型”列表

type L1 = { 
    Id : int32 // Common id 
    StringFieldA : string 
    StringFieldB : string 
} 

type L2 = { 
    Id : int32 // Common id 
    Ratio: decimal 
    StringFieldC : string 
} 

type L3 = { 
    Id : int32 // Common id 
    Mean: decimal 
    StringFieldD : string 
} 

我有方法,返回F#名单以上各项。我现在想合并3所列出,不同的“类型”为一体的 - 基于共同的ID - 一个列表如下:

type Merged = { 
    Id : int32 
    StringFieldA : string 
    StringFieldB : string 
    StringFieldC : string 
    StringFieldD : string 
    Mean: decimal 
    Ratio: decimal 
} 

我怎么能在F#做到这一点?对不起,如果我错过了其他地方的样本。

回答

2

假设他们正在整理和长度相等的(如果那不是我不知道什么合并的结果应该如此):我不认为这会为了什么工作

List.zip3 l1 l2 l3 |> List.map (fun (l1, l2, l3) -> 
    { Id = l1.Id 
    StringFieldA = l1.StringFieldA 
    StringFieldB = l1.StringFieldB 
    StringFieldC = l2.StringFieldC 
    StringFieldD = l3.StringFieldD 
    Mean = l3.Mean 
    Ratio = l2.Ratio }) 
+0

是的 - 他们都排序和完全相同的长度 - 关于同一组织的数据,只是通过不同的输入(不是我的设计...) –

+0

然后这应该工作得很好。 – Daniel

+0

谢谢丹尼尔,那样做。 –

0

我想这是你想要的 - 可识别联合

type Data = 
    |First of L1 
    |Second of L2 
    |Third of L3 

,你可以再增加一个ID件类似

with member x.Id = 
    match x with 
    |First(a) -> a.Id 
    |Second(a) -> a.Id 
    |Third(a) -> a.Id 
0

也许你可以通过ID进行排序各列表和它们压缩如果所有列表都具有相同的ID集合。

+0

他想 - 你最终会得到一个'(L1 * L2 * L3)列表'。它还要求所有三个输入具有相同的长度 –

+0

Zip不是最后一个操作,您还需要将元组映射到所需的最终数据。 –