F#-了解使用泛型的类型 [英] F# - Understanding types that use generics

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

问题描述

我要在10天之内参加F#考试,而且由于我目前正在做旧的考试,所以在理解泛型(尤其是具有两个多态参数的类型)时遇到了一个问题.

I am having an F# exam in 10 days and as I am currently doing old exam sets, I ran into a problem understanding generics and especially types that have two polymorphic arguments.

这些问题应该很容易解决,但是我不确定它在语法上是如何工作的. 旧考试题如下:

The questions should be rather easy to solve, but how it works syntactically, I am not sure. The old exam question is as follows:

以下类型Sum<'a,'b>包含两种不同的值

The following type Sum<'a,'b> comprises two different kinds of values

type Sum<'a,'b> = 
| Left of 'a
| Right of 'b

现在我需要编写两个类型为Sum<int list, bool option>的值,一个应使用Left定义,另一个应使用Right.

Now I need to write two values of type Sum<int list, bool option>, one should be defined using Left and the other Right.

如果定义let sum1 = Left "Hello World,则其评估结果为val sum1 : Sum<string,'a>,但是我找不到创建Sum<int list, bool option>的方法.

If you define let sum1 = Left "Hello World it evaluates to val sum1 : Sum<string,'a>, but I cannot find a way to create Sum<int list, bool option>.

您将如何解决?

推荐答案

如果要编写

let sum1 = Sum<string,int>.Left "Hello World"

您会得到一个Sum<string,int>

所以如果您需要Sum<int list, bool option>,那么.....

so if you need a Sum<int list, bool option> then.....

(公平地说,在现实生活中,拥有Sum<string,'a>并不是真正的问题,因为'a可以变成任何东西,如果需要成为bool option或其他任何东西,类型推断通常会很费劲为您而限制'a).

(to be fair, in real life, having a Sum<string,'a> is not really an issue as 'a can become anything and if it needs to be a bool option or whatever, the type inference will usually do the hard work for you and constrain 'a).

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

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