代码之家  ›  专栏  ›  技术社区  ›  sdgfsdh

我可以为自己的类型使用特殊的泛型语法吗?

  •  4
  • sdgfsdh  · 技术社区  · 6 年前

    int list // instead of List<int>
    int option // instead of Option<int>
    
    • 这个语法叫什么?
    • 我能为自己的类型启用它吗?
    2 回复  |  直到 6 年前
        1
  •  5
  •   DaveShaw Thishin    5 年前

    它包含在 MSDN on F# Types

    在“泛型类型”下:

    类型参数泛型类型名称| 'a list

    或者

    list<'a>

    以及“构造类型”:

    类型参数泛型类型名称

    泛型类型名称<类型参数列表>

    type dave<'a> = {
        V : 'a
    };;
    
    let stringDave: dave<string> = { V = "string" };;
    //val stringDave : dave<string> = {V = "string";}
    
    let intDave : int dave = { V = 123 };;
    //val intDave : dave<int> = {V = 123;}
    
    
        2
  •  3
  •   TheQuickBrownFox    6 年前

    首先,需要注意的是 list List 与前缀和后缀语法没有直接关系。类型 'T list 只是类型的别名 List<'T> . 从 F# core source code

    type List<'T> = 
       | ([])  :                  'T list
       | (::)  : Head: 'T * Tail: 'T list -> 'T list
       interface System.Collections.Generic.IEnumerable<'T>
       interface System.Collections.IEnumerable
       interface System.Collections.Generic.IReadOnlyCollection<'T>
       interface System.Collections.Generic.IReadOnlyList<'T>
    
    and 'T list = List<'T>
    

    除此之外,我们还可以表示任何泛型类型前缀或后缀。

    结合这两种情况,这意味着所有这些类型都是有效的和等价的。

    int list
    int List
    list<int>
    List<int>
    

    这适用于任何其他.NET类型,例如。 int System.Collections.Generic.HashSet ,以及您自己的类型:

    type MyCoolType<'a> = A | B
    
    let x : int MyCoolType = A
    // compiles ✔