F# - Understanding types that use generics

独自空忆成欢 提交于 2020-06-23 16:06:31

问题


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:

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

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

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

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

How would you solve it?


回答1:


if you were to write

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

you would get a Sum<string,int>

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

(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).



来源:https://stackoverflow.com/questions/61816967/f-understanding-types-that-use-generics

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!