何时在F#中使用区分联合与记录类型 [英] When to use a Discriminate Union vs Record Type in F#

查看:87
本文介绍了何时在F#中使用区分联合与记录类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在尝试复杂的示例之前,我试图弄清楚F#的基础知识.我正在学习的材料介绍了区分联合和记录类型.我已经审查了这两种材料,但是我仍然不清楚为什么我们要在另一种材料上使用.

I am trying to get the basics of F# clear before moving on to complex examples. The material I'm learning has introduced both Discriminate Unions and Record types. I have reviewed the material for both, but it is still unclear to me why we would use one over the other.

我创建的大多数玩具示例似乎都可以实现.记录似乎与我在C#中作为对象的想法非常接近,但我试图避免依赖于映射到c#作为理解F#的方式

Most of the toy examples I have created seem to be implementable in both. Records seem to be very close to what I think of as an object in C#, but I am trying to avoid relying on mapping to c# as a way to understand F#

所以...

  • 是否有明确的理由要使用一种方法?

  • Are there clear reason to use one over the other?

是否存在某些适用的典型情况?

Are there certain canonical cases where one applies?

其中是否有某些功能可用,但没有 其他?

Are there certain functionalities available in one, but not the other?

推荐答案

将其视为记录为和",而有区别的并集为或". 这是一个字符串和一个整数:

Think of it as a Record is 'and', while a discriminated union is 'or'. This is a string and an int:

type MyRecord = { myString: string
                  myInt: int }

这是一个字符串或整数值,但不能同时是这两个值:

while this is a value that is either a string or an int, but not both:

type MyUnion = | Int of int
               | Str of string

此虚拟游戏可以在标题"屏幕,游戏中或显示最终分数,但只能是其中一个选项.

This fictitious game can be in the Title screen, In-game, or displaying the final score, but only one of those options.

type Game =
  | Title
  | Ingame of Player * Score * Turn
  | Endgame of Score

这篇关于何时在F#中使用区分联合与记录类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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