在 F# 中统一不同来源的(推文/记录类型)
我从三个不同的来源获取推文,每个来源都有或多或少的数据,每个来源给我一个记录类型的序列。比方说:
type Tweet1 = { id:int64; text:string;}
type Tweet2 = { id:int64; text:string; user_name:string}
type Tweet3 = { id:int64; text:string; user_name:string; date:DateTime}
如何统一三个序列 seq
?
我正在考虑使用:
- 一个接口,但在向上转换时我会丢失数据(而且我似乎无法获得记录类型来实现接口)
- 使用反射自动创建一个记录类型,其中所有属性选项类型除外,共享的选项类型除外,然后将所有记录类型映射到这个记录类型,但这似乎不太自然
有什么想法吗?
谢谢
I am getting tweets from three different sources, and each source has more or less data, each source gives me a seq of record types. Let's say:
type Tweet1 = { id:int64; text:string;}
type Tweet2 = { id:int64; text:string; user_name:string}
type Tweet3 = { id:int64; text:string; user_name:string; date:DateTime}
How does one go about to unify the three sequences, seq<Tweet1>, seq<Tweet2>, seq<Tweet3>
?
I was thinking about using:
- an interface but then I wil lose data when upcasting ( also I cant seem to get a record type to implement an intertface )
- Creating automaticaly a record type with Reflection with all proprietes option type except the ones that are shared, and then map all the record types to this one, but that does not seem very natural
Any ideas?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
也许最简单的选择是定义一个包含所有信息的记录,但那些可能丢失的记录将存储为
option
值(并且当信息被填充时将用None
填充)不可用):我能想到的另一种方法是使用如下数据结构存储有关推文的信息:
第一条记录中的值将转换为
Tweet(id, text)
和最后一条记录将变成WithDate(发布,WithUser(用户,推文(id,文本)))
。list
类型的集合可以组合普通推文以及带有附加信息的推文。从架构上来说,这有点类似于装饰器设计模式,因为您可以向基本推文结构添加附加信息。这可能并不比基本记录更有用,但您可以使用此技巧来添加更多通用性。
您还可以添加成员以提取属性(使用成员语法)。日期和用户信息可能会返回
option
和option
。Probably the easiest option is to define a record that contains all information, but those that may be missing are stored as
option
values (and will be filled withNone
when the information is not available):Another way I can think of is to store information about tweets using a data structure like this:
The values from the first record would be turned into
Tweet(id, text)
and the values of the last record would be turned intoWithDate(posted, WithUser(user, Tweet(id, text)))
. A collection of typelist<TweetInfo>
can combine both plain tweets as well as tweets with additional information.Architecturally, this is a bit similar to the decorator design pattern, because you can add additional information to the basic tweet structure. This probably isn't more useful than the basic record, but you can use this trick to add more generality.
You can also add members to extract the properties (using the member syntax). A date and user information would probably return
option<DateTime>
andoption<string>
.