在F#的lambda前pression返回不同类型的数组 [英] Returning different types of arrays from a lambda expression in F#

查看:136
本文介绍了在F#的lambda前pression返回不同类型的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个记录列表

 键入项目= {颜色:字符串;尺寸:INT}
让ITEMLIST = {[颜色=红;大小= 1};
                {颜色=绿色;大小= 2};
                {颜色=蓝;大小= 3}]

我希望得到把我的记录列表转换值的数组像
[|红,绿,蓝|]或[| 1; 2; 3 |]

我可以八九不离十那里像这样

 键入的ItemType =
|字符串的颜色
|为int的大小键入ItemEnum =
| C
|小号让GetProp X Y =
赛果与
| C - > List.toArray Y |> Array.map(好玩点¯x - > ItemType.Color(x.Color))
|的S - > List.toArray Y |> Array.map(好玩点¯x - > ItemType.Size(x.Size))

但是当我打电话 GetProp小号ITEMLIST 我回来[|大小1;尺寸2;大小3 |]。有用的,但不正是我要找的。

我试过以下

 让GetProp2 X Y:有[] =
赛果与
|颜色 - > List.toArray Y |> Array.map(好玩点¯x - > x.Color)
|尺寸 - > List.toArray Y |> Array.map(好玩点¯x - > x.Size)

但它不喜欢的两个不同的返回类型。

我愿意就这样做的不同(更多的功能?)的方式提出建议,并会AP preciate输入。


解决方案

自定义变量类型的确是去这里的方式(一般无论你需要一个类型,是X或Y)。然而,定义,你的函数看起来像它可能返回一个数组,其中颜色尺寸混合,但在实践看来你只希望它返回一个或另一个。如果是这样,这是最好的体现在类型:

 键入项目=
|字符串的颜色[]
|为int的尺寸[]让GetProp点¯xYS =
赛果与
| C - >颜色[|在伊苏Ÿ - > y.Color |]
|的S - >尺寸[|在伊苏Ÿ - > y.Size |]

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

i have a List of records

type Item = { Color : string; Size : int}
let itemList = [{Color="Red"; Size=1};
                {Color="Green"; Size=2};
                {Color="Blue"; Size=3};]

I am looking to get turn my list of records into an array of values like [|"Red";"Green";"Blue"|] or [|1;2;3|]

I can sorta get there like this

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))

but when I call GetProp S itemList I get back [|Size 1; Size 2; Size 3|]. Useful but not exactly what I'm looking for.

I've tried the following

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)

but it doesn't like the two different return types.

I'm open to suggestions on different (more functional?) ways of doing this and would appreciate your input.

解决方案

A custom variant type is indeed the way to go here (and generally wherever you need a type that is "either X or Y"). However, as defined, your function looks like it might return an array in which Color and Size are mixed, but in practice it seems that you only want it to return one or the other. If so, this is best reflected in the types:

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 |]

By the way, is there any particular reason why you use array for return type here, rather than the usual lazy sequence (seq)?

这篇关于在F#的lambda前pression返回不同类型的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆