gpt4 book ai didi

list - 对联合类型的 F# 列表进行操作

转载 作者:行者123 更新时间:2023-12-03 18:26:39 25 4
gpt4 key购买 nike

这是我在 F# List of Union Types 上的问题的延续.感谢有用的反馈,我能够创建一个列表 Report s,与 Report要么 DetailSummary .这是数据定义:

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

现在我已经得到了 Report 的列表s 位于名为 reports 的变量中,我想遍历那些 Report对象并根据每个对象执行操作。除了处理 Detail.Divisions 的情况外,操作是相同的。或 Summary.Office .显然,我必须以不同的方式处理这些。但我不想复制所有处理类似 State 的代码。和 Sections每个。

我的第一个(工作)想法如下:
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 ,不知道是哪个, DetailSummary ,并且也无法访问属性。我想转换 report到相应的 DetailSummary然后使用相同的代码处理任何一种情况,除了 Detail.DivisionsSummary.Office .有没有办法做到这一点?

谢谢。

最佳答案

你可以这样做:

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

关于list - 对联合类型的 F# 列表进行操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13804444/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com