从F#中的lambda表达式返回不同类型的数组

Rob*_*lls 1 arrays lambda f# types record

我有一份记录清单

type Item = { Color : string; Size : int}
let itemList = [{Color="Red"; Size=1};
                {Color="Green"; Size=2};
                {Color="Blue"; Size=3};]
Run Code Online (Sandbox Code Playgroud)

我希望将我的记录列表转换为一系列值,如[|"Red";"Green";"Blue"|]或[| 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))
Run Code Online (Sandbox Code Playgroud)

但是当我打电话的时候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)
Run Code Online (Sandbox Code Playgroud)

但它不喜欢两种不同的返回类型.

我愿意接受有关不同(更多功能性)方法的建议,并希望得到您的意见.

Pav*_*aev 5

自定义变体类型确实是这里的方式(通常在任何需要"X或Y"的类型的地方).但是,根据定义,您的函数看起来可能会返回一个数组,其中Color并且Size是混合的,但在实践中,您似乎只希望它返回一个或另一个.如果是这样,这最好反映在类型中:

type Items =
| Colors of string[]
| Sizes of int[]

let GetProp x ys =
match x with
| C -> Colors [| for y in ys -> y.Color |]
| S -> Sizes [| for y in ys -> y.Size |]
Run Code Online (Sandbox Code Playgroud)

顺便说一下,有没有什么特别的理由为什么你在这里使用数组返回类型,而不是通常的懒惰序列(seq)?