问题
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