我有一個記錄列表在F#lambda表達式返回不同類型的數組
type Item = { Color : string; Size : int}
let itemList = [{Color="Red"; Size=1};
{Color="Green"; Size=2};
{Color="Blue"; Size=3};]
我希望得到把我的記錄列表到值的數組一樣 [|「紅」; 「綠」, 「藍」 |]或[| 1; 2; 3 |]
我可以八九不離十那裏像這樣
type ItemType =
| Color of string
| Size of int
type ItemEnum =
| C
| S
let GetProp x y =
match x with
| C -> List.toArray y |> Array.map(fun x -> ItemType.Color(x.Color))
| S -> List.toArray y |> Array.map(fun x -> ItemType.Size(x.Size))
,但是當我打電話GetProp S itemList
我回來[|大小1;大小2;大小3 |]。有用但不完全是我要找的。
我已經試過以下
let GetProp2 x y : 'a[] =
match x with
| Color -> List.toArray y |> Array.map(fun x -> x.Color)
| Size -> List.toArray y |> Array.map(fun x -> x.Size)
,但它並不像兩個不同的返回類型。
我很樂意接受有關不同(更實用?)方法的建議,並希望得到您的意見。
該數組是下一個我使用的外部庫所需的參數類型。我將如何從記錄列表轉到特定值的seq? – RobRolls 2009-12-19 08:48:29
任何列表已經是一個seq,任何數組也是如此。在.NET中,seq是'IEnumerable'。如果你需要從任意一個隨機序列(也可能是一個懶序列)中創建一個數組或一個列表,那麼'Seq.toArray'和'Seq.toList'就可以完成。 –
2009-12-19 09:58:46