对联合类型的F#列表进行操作 [英] Operating on an F# List of Union Types
问题描述
这是我在 F#联合类型列表上的问题的继续.多亏了有用的反馈,我得以创建Report
的列表,其中Report
是Detail
或Summary
.再次是数据定义:
This is a continuation of my question at F# List of Union Types. Thanks to the helpful feedback, I was able to create a list of Report
s, with Report
being either Detail
or Summary
. Here's the data definition once more:
module Data
type Section = { Header: string;
Lines: string list;
Total: string }
type Detail = { State: string;
Divisions: string list;
Sections: Section list }
type Summary = { State: string;
Office: string;
Sections: Section list }
type Report = Detail of Detail | Summary of Summary
现在我已经在名为reports
的变量中获得了Report
的列表,我想遍历那些Report
对象并基于每个对象执行操作.除了处理Detail.Divisions
或Summary.Office
的情况外,其他操作相同.显然,我必须以不同的方式处理这些问题.但是我不想重复所有用于处理相似的State
和Sections
的代码.
Now that I've got the list of Report
s in a variable called reports
, I want to iterate over those Report
objects and perform operations based on each one. The operations are the same except for the cases of dealing with either Detail.Divisions
or Summary.Office
. Obviously, I have to handle those differently. But I don't want to duplicate all the code for handling the similar State
and Sections
of each.
我的第一个(可行的)想法如下:
My first (working) idea is something like the following:
for report in reports do
let mutable isDetail = false
let mutable isSummary = false
match report with
| Detail _ -> isDetail <- true
| Summary _ -> isSummary <- true
...
这将使我知道何时处理Detail.Divisions
而不是Summary.Office
.但这并没有给我一个可以使用的对象.我仍然停留在report
上,不知道它是Detail
还是Summary
,并且也无法访问属性.我想将report
转换为适当的Detail
或Summary
,然后使用相同的代码来处理任一情况,但Detail.Divisions
和Summary.Office
除外.有办法吗?
This will give me a way to know when to handle Detail.Divisions
rather than Summary.Office
. But it doesn't give me an object to work with. I'm still stuck with report
, not knowing which it is, Detail
or Summary
, and also unable to access the attributes. I'd like to convert report
to the appropriate Detail
or Summary
and then use the same code to process either case, with the exception of Detail.Divisions
and Summary.Office
. Is there a way to do this?
谢谢.
推荐答案
您可以执行以下操作:
for report in reports do
match report with
| Detail { State = s; Sections = l }
| Summary { State = s; Sections = l } ->
// common processing for state and sections (using bound identifiers s and l)
match report with
| Detail { Divisions = l } ->
// unique processing for divisions
| Summary { Office = o } ->
// unique processing for office
这篇关于对联合类型的F#列表进行操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!