F#联合类型列表 [英] F# List of Union Types

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

问题描述

我想要一份报告列表.报表可以是明细或栏目类型.

I want a list of Reports. Report can be either Detail or Section types.

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

然后在我的代码中,我想执行以下操作:

Then in my code, I'd like to do the following:

let mutable (reports:Report list) = []

...

reports <- detail::reports
// or
reports <- summary::reports

在第一种情况下,编译器会抱怨:该表达式应该具有Report类型,但在这里具有Detail类型",在第二种情况下也是如此.

The compiler complains in the first case: "The expression was expected to have type Report but here has type Detail", and appropriately similarly in the second case.

我是否想做这样的事情吗?我应该以不同的方式思考这个问题吗?由于报告"是详细信息"或摘要",因此报告"列表不应该接受详细信息"或摘要"吗?如果不是详细列表或摘要列表,什么是报告列表?

Am I out of my mind for wanting to do such a thing? Should I be thinking about the problem differently? Because Report is either Detail or Summary, shouldn't a list of Report accept either a Detail or a Summary? What is a Report list if not a list of Detail or Summary?

谢谢.

推荐答案

您的语法有点错误:

type Report = Detail of Detail | Summary of Summary

reports <- (Detail detail)::reports
// or
reports <- (Summary summary)::reports

在您的代码中,您基本上只是将Report类型定义为具有两个可能值DetailsSummary的枚举(在这些情况下,它们类似于标签,而不是不同子类型的类型). F#中的已区分联合具有显式标记,因此您还必须使用联合构造器之一来创建要放入列表的实例.

In your code you've basically just defined the Report type to be an enum with the two possible values Details or Summary (these are like labels, not the types of different subtypes in this context). Discriminated unions in F# are explicitly tagged, so you've also got to use one of the union constructors to create an instance to put into the list.

这篇关于F#联合类型列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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