F# type definition syntax

五迷三道 提交于 2021-02-19 05:25:06

问题


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

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