F#类型的后缀关键字

Mas*_*ano 3 f#

据我所知,F#中的Option和List类型有一个特殊的符号。例如,Option<'a>它与写作相同'a option,因此for 'a listFSharpList<'a>

是这些特定的语言关键字,还是有一种定义自定义类型的方法,这些自定义类型可以使用“ post-fix”表示法相同list且相同option

rmu*_*unn 5

您可以对要定义的任何F#类型执行此操作。您不会获得名称的自动小写版本...但是F#内置类型也没有:在FSharp.Core/prim-types.fsF#源代码中,有一个定义type 'a list = List<'a>,这就是为什么可以编写int list而不是的原因List<int>

并且在定义类型时也可以使用Foo<'a>'a Foo(或'a foo)。唯一的规则是,您必须匹配定义类型时使用的大小写样式。这是一个F#交互式会话,以演示:

> type Foo<'a> = 'a list ;;
type Foo<'a> = 'a list

> type 'a bar = 'a list ;;
type 'a bar = 'a list

> let x : int Foo = [] ;;
val x : Foo<int> = []

> let y : Foo<int> = [] ;;
val y : Foo<int> = []

> let z : int bar = [] ;;
val z : int bar = []

> let w : bar<int> = [] ;;
val w : int bar = []
Run Code Online (Sandbox Code Playgroud)

但是您必须匹配您定义的类型的大小写:

> let x : int foo = [] ;;

  let x : int foo = [] ;;
  ------------^^^

error FS0039: The type 'foo' is not defined. Maybe you want one of the following:
   Foo
   Foo`1

> let y : Bar<int> = [] ;;

  let y : Bar<int> = [] ;;
  --------^^^

error FS0039: The type 'Bar' is not defined. Maybe you want one of the following:
   bar
   bar`1
Run Code Online (Sandbox Code Playgroud)

请注意,Foo<int>无论我们将类型定义为int Foo还是,我们都将获得F#Interactive响应中列出的类型Foo<int>。这不是基于我们用来定义类型的大小写(大写或小写),而是基于我们使用的前缀/后缀顺序:

> type foo<'a> = 'a list ;;
type foo<'a> = 'a list

> type 'a bar = 'a list ;;
type 'a bar = 'a list

> let x : 'a foo = [] ;;
val x : foo<'a>

> let y : 'a bar = [] ;;
val y : 'a bar
Run Code Online (Sandbox Code Playgroud)

所以你去了。您可以对自己的类型使用此语法,而无需执行任何特殊操作。唯一的规则是类型必须完全采用一个通用参数:您不能这样做type d = int,string Dictionary。对于带有两个或多个通用参数的类型,必须使用Dictionary<int,string>样式定义它们。