对联合类型的F#列表进行操作 [英] Operating on an F# List of Union Types

查看:61
本文介绍了对联合类型的F#列表进行操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在 F#联合类型列表上的问题的继续.多亏了有用的反馈,我得以创建Report的列表,其中ReportDetailSummary.再次是数据定义:

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 Reports, 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.DivisionsSummary.Office的情况外,其他操作相同.显然,我必须以不同的方式处理这些问题.但是我不想重复所有用于处理相似的StateSections的代码.

Now that I've got the list of Reports 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转换为适当的DetailSummary,然后使用相同的代码来处理任一情况,但Detail.DivisionsSummary.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屋!

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