问题
I'm working on the '99 problems of F#', and saw the following definition of NestedList
:
type 'a NestedList = List of 'a NestedList list | Elem of 'a
I'm a little confused by the syntax here, as normally there is only a type name after the type
. Can someone clarify it? Thanks!
回答1:
This is a discriminated union in a condensed syntax. You can also write it as:
type 'a NestedList =
| List of 'a NestedList list
| Elem of 'a
or
type NestedList<'a> =
| List of NestedList<'a> list
| Elem of 'a
This is using generics, where the type itself is taking another type as an argument.
回答2:
F# has two ways of specifying a generic type:
- C#/.NET style -
SomeType<'a, 'b>
- OCaml/ML style -
('a * 'b) SomeType
Those are really two ways of saying the same thing and can be used interchangeably. Which one to use is a matter of preference and code standards. Usually people use OCaml style for basic F# types like list, array or option, and C# style for user-defined and BCL ones.
回答3:
So this is a definition of a generic discriminated union with generic type 'a
.
The key idea is that each element has the type 'a
.
来源:https://stackoverflow.com/questions/26568037/f-type-definition-syntax